Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Java function #178

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions java/generate_screenshot/Index.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import com.google.gson.Gson;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.util.UUID;

/**
* @Author:Shizhan
* @ProjectName:screenshot
* @currentTime: 2023/7/26 16:02
*/

public RuntimeResponse main(RuntimeRequest req, RuntimeResponse res) throws AWTException, URISyntaxException, IOException {
String payloadString = req.getPayload();
final Gson gson = new Gson();
Map<String, Object> payload = gson.fromJson(payloadString, Map.class);
Map<String, Object> responseData = new HashMap<>();
//get the url
String urlInput = payload.get("url").toString();
//test if the url is valid
long lo = System.currentTimeMillis();
boolean isValid = false;
URL url;
try {
url = new URL(urlInput);
InputStream in = url.openStream();
//the input is true
isValid = true;
} catch (Exception e1) {
//the input is false
url = null;
}
//if the url is not valid, return false
if(!isValid){
responseData.put("success",false);
responseData.put("message","Website could not be reached.");
return res.json(responseData);
}
//get the absolute path
File file = new File("src/main/resources/upload");
String pathname = file.getAbsolutePath();
//JDK 1.6 and up
Desktop.getDesktop().browse(new URI(urlInput));
Robot robot = new Robot();
robot.delay(5000);
Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int width = (int) d.getWidth();
int height = (int) d.getHeight();
//maximize the browser.
robot.keyPress(KeyEvent.VK_F11);
robot.delay(2000);
Image image = robot.createScreenCapture(new Rectangle(0, 0, width, height));
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics q = bi.createGraphics();
q.drawImage(image, 0, 0, width, height, null);
//get the File
File outputfile = new File(pathname + "/"+ UUID.randomUUID() +".jpg");
//get the absolute path
String absolutePath = outputfile.getAbsolutePath();
ImageIO.write(bi, "jpg", outputfile);

// transfer to base 64 format.
byte[] fileByte = null;
String base64Str = "";
try {
File fileNew = new File(absolutePath);
fileByte = Files.readAllBytes(fileNew.toPath());
base64Str = "data:image/png;base64," + Base64.encodeBase64String(fileByte);
} catch (IOException e) {
//return the false message
e.printStackTrace();
responseData.put("success",false);
responseData.put("message","Website could not be reached.");
return res.json(responseData);
}
//return the corrent value.
responseData.put("success", true);
responseData.put("screenshot", base64Str);
return res.json(responseData);
}
61 changes: 61 additions & 0 deletions java/generate_screenshot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# 💻 Get Short URL

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be # Get Screenshot


A Java Cloud Function to get price of crypto.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be rectified to mention that this function is used to generate srceenshots, also mention the file types supported


```json
{
"payload": {
"url": "https://google.com/"
}
}
```

_Example output:_


```json
{
"success":true,
"screenshot":"iVBORw0KGgoAAAANSUhEUgAAAaQAAALiCAY...QoH9hbkTPQAAAABJRU5ErkJggg=="
}
```

_Error Example output:_

```json
{
"success": false,
"message":"Website could not be reached."
}
```


## 📝 Environment Variables

List of environment variables used by this cloud function.

## 🚀 Deployment

1. Clone this repository, and enter this function folder:

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd java/generate_screenshot
```

2. Enter this function folder and build the code:
```
docker run -e INTERNAL_RUNTIME_ENTRYPOINT=Index.java --rm --interactive --tty --volume $PWD:/usr/code openruntimes/java:v2-18.0 sh /usr/local/src/build.sh
```
As a result, a `code.tar.gz` file will be generated.

3. Start the Open Runtime:
```
docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/java:v2-18.0 sh /usr/local/src/start.sh
```

Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Java runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/java-18.0).

## 📝 Notes
- This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions).
- This example is compatible with Java 18.0. Other versions may work but are not guarenteed to work as they haven't been tested.
4 changes: 4 additions & 0 deletions java/generate_screenshot/deps.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'org.apache.tomcat:tomcat-util:8.5.23'
}