### Example Dependency Tree Output
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Displays a dependency tree of Python packages, showing required and installed versions.
```text
vaderSentiment==3.3.2
└── requests [required: Any, installed: 2.32.3]
├── certifi [required: >=2017.4.17, installed: 2024.8.30]
├── charset-normalizer [required: >=2,<4, installed: 3.1.0]
├── idna [required: >=2.5,<4, installed: 3.8]
└── urllib3 [required: >=1.21.1,<3, installed: 2.2.2]
```
--------------------------------
### Generate Maven Project and Navigate Directory
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-rust-code-guide/README.md
Generates a new Maven project using the quickstart archetype and changes the current directory to the newly created project. Ensure you have Maven installed.
```shell
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.5 -DgroupId=com.example -DartifactId=demo -DinteractiveMode=false
cd demo
```
--------------------------------
### Install GraalVM with SDKMAN!
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-starter/README.md
Installs GraalVM version 25.0.2-graal using SDKMAN!. Ensure JAVA_HOME is set correctly.
```bash
sdk install java 25.0.2-graal
```
--------------------------------
### Build and Run Go Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Set Go environment variables, package the application, and then execute it using Maven. This assumes a standard Go compiler setup.
```shell
# Use Go compiler
export GOROOT=$(go env GOROOT)
# or use TinyGo
export TINYGOROOT=$(tinygo env TINYGOROOT)
# Package the application
mvn package
# Run the application
mvn exec:exec
```
--------------------------------
### Run the Micronaut Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-micronaut-photon/README.md
Starts the Micronaut demo application using the Maven wrapper. Access the application at http://localhost:8080/.
```bash
./mvnw mn:run
```
--------------------------------
### Example Dependency Output
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Sample output from the 'pip3 freeze -l' command, showing pinned package versions.
```text
certifi==2024.8.30
charset-normalizer==3.1.0
idna==3.8
requests==2.32.3
urllib3==2.2.2
vaderSentiment==3.3.2
```
--------------------------------
### Activate Virtual Environment and Install Package
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Activates the created virtual environment and installs the 'art' Python package version 6.3 using pip. This makes the package available for use.
```shell
> . {path/to/graalpy-standalone}/bin/activate
> python --version
> pip install art==6.3
```
--------------------------------
### Package Application with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Builds the application and installs transitive dependencies into a virtual environment using Gradle.
```shell
./gradlew assemble
```
--------------------------------
### Generate Maven Project
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Generates a basic Maven project using the quickstart archetype. This is the initial step for creating the Java application.
```shell
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.5 \
-DgroupId=example -DartifactId=example -Dpackage=org.example \
-Dversion=1.0-SNAPSHOT -DinteractiveMode=false
```
--------------------------------
### Wasm Debugging Server Details (DAP)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-micronaut-photon/README.md
Example output indicating that the Graal DAP server has started and is listening on a specific port for debugging connections.
```bash
__ __ _ _
| \/ (_) ___ _ __ ___ _ __ __ _ _ _| |_
| |\/| | |/ __| '__/ _ \| '_ \ / _` | | | | __|
| | | | | (__| | | (_) | | | | (_| | |_| | |_
|_| |_|_|\___|_| \___/|_| |_|\__,_|\__,_|\__|
[Graal DAP] Starting server and listening on localhost/127.0.0.1:4711
```
--------------------------------
### Install JBang
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-jbang-qrcode/README.md
Installs JBang using SDKMAN!. This tool is used to run the GraalPy script.
```bash
sdk install jbang
```
--------------------------------
### Create New Maven Java Project
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Generates a new Maven project using the Maven Quickstart Archetype. This command sets up a basic Java project structure.
```shell
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.5 -DgroupId=com.example -DartifactId=qrdemo -DinteractiveMode=false
cd qrdemo
```
--------------------------------
### Run Micronaut Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-micronaut-pygal-charts/README.md
Packages the Micronaut application and starts the demo. Access the application via the provided URLs to view different chart rendering approaches.
```bash
./mvnw package mn:run
```
--------------------------------
### GraalPy DAP Server Output
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-scripts-debug-guide/README.md
Example output indicating that the GraalPy Debug Adapter Protocol (DAP) server has started and is listening for connections on the specified host and port.
```text
[Graal DAP] Starting server and listening on localhost/127.0.0.1:4711
```
--------------------------------
### Compile and Run Application with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-scripts-debug-guide/README.md
Commands to assemble and run a Java application using Gradle. Ensure you have Gradle installed or are using the Gradle wrapper.
```shell
./gradlew assemble
./gradlwe run
```
--------------------------------
### Configure Frontend Maven Plugin
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Configures the frontend-maven-plugin in the POM file to automate Node.js installation, npm package installation, and Webpack bundling. This ensures JavaScript dependencies are managed and packaged for integration.
```xml
com.github.eirslett
frontend-maven-plugin
1.15.0
v21.7.2
src/main/js
target
install node and npm
install-node-and-npm
npm install
npm
webpack build
webpack
--mode production
${project.build.outputDirectory}/bundle
```
--------------------------------
### Freeze Dependencies (Windows - Maven)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Lists installed Python packages in the virtual environment for Maven projects on Windows.
```shell
.\target\classes\org.graalvm.python.vfs\venv\Scripts\pip3.exe freeze -l
```
--------------------------------
### Compile and Run Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-scripts-debug-guide/README.md
Commands to compile and run a Java application using Maven. Ensure you have Maven installed or are using the Maven wrapper.
```shell
./mvnw compile
./mvnw javafx:run
```
--------------------------------
### Configure Gradle Node Plugin
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Set up the Gradle Node plugin to manage Node.js and npm installations, and define tasks for JavaScript bundling.
```gradle
plugins {
id 'java'
id 'application'
id 'com.github.node-gradle.node' version '7.0.1' // ①
}
node {
version = '22.14.0'
npmVersion = '10.9.2'
download = true
workDir = file("\{project\.buildDir\}/node")
npmWorkDir \= file\("{project.buildDir}/npm")
nodeProjectDir = file('src/main/js')
}
tasks.register('webpackBuild', NpmTask) {
dependsOn tasks.npmInstall
workingDir = file('src/main/js')
args = ['run', 'build']
environment = ['BUILD_DIR': "${buildDir}/classes/java/main/bundle"]
}
processResources.dependsOn tasks.webpackBuild // ④
```
--------------------------------
### Freeze Dependencies (Windows - Gradle)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Lists installed Python packages in the virtual environment for Gradle projects on Windows.
```shell
.\app\build\generated\graalpy\resources\org.graalvm.python.vfs\venv\Scripts\pip3.exe freeze -l
```
--------------------------------
### Compile Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-native-extensions-guide/README.md
Use Maven to package your Java application, which includes installing Python dependencies with native extensions.
```shell
mvn package
```
--------------------------------
### Setup JavaFX Window for File Comparison
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-scripts-debug-guide/README.md
This Java code sets up a JavaFX window with a text element that acts as a drop target for files. It includes drag-and-drop event handlers to accept files for comparison and provides visual feedback.
```java
private void setupWindow(Stage stage) {
stage.setTitle("Similarity score");
StackPane root = new StackPane();
Scene scene = new Scene(root, 800, 200);
final Text target = new Text(200, 100, "DROP FILES HERE");
target.setTextAlignment(TextAlignment.CENTER);
resetTargetColor(target);
target.setScaleX(2.0);
target.setScaleY(2.0);
StackPane.setMargin(target, new Insets(10, 10, 10, 10));
target.setOnDragOver((event) -> {
if (event.getGestureSource() != target && event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.ANY);
}
event.consume();
}
);
target.setOnDragEntered((event) -> {
if (event.getGestureSource() != target && event.getDragboard().hasFiles() && event.getDragboard().getFiles().size() == 2) {
target.setFill(Color.GREEN);
} else {
target.setText("Drop 2 files to compare.");
}
event.consume();
}
);
target.setOnDragExited((event) -> {
resetTargetColor(target);
event.consume();
});
setupFileComparison(target);
root.getChildren().add(target);
stage.setScene(scene);
stage.show();
if (getParameters().getRaw().contains("CI")) {
stage.close();
}
}
private static void resetTargetColor(final Text target) {
target.setFill(Color.LIGHTGRAY);
}
```
--------------------------------
### Freeze Dependencies (macOS/Linux - Maven)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Lists installed Python packages in the virtual environment for Maven projects on macOS and Linux.
```shell
./target/classes/org.graalvm.python.vfs/venv/bin/pip3 freeze -l
```
--------------------------------
### Test Python Package in GraalPy REPL
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Starts the GraalPy REPL within the activated virtual environment and imports the 'art' package to verify its functionality by generating ASCII art.
```python
>>> import art
>>> print(art.text2art("GraalPy"))
```
--------------------------------
### Wasm Debugging Session Details (Chrome DevTools)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-micronaut-photon/README.md
Example output indicating that the debugger is listening and providing a link to connect via Chrome DevTools or IntelliJ Ultimate.
```bash
__ __ _ _
| \/ (_) ___ _ __ ___ _ __ __ _ _ _| |_
| |\/| | |/ __| '__/ _ \| '_ \ / _` | | | | __|
| | | | | (__| | | (_) | | | | (_| | |_| | |_
|_| |_|_|\___|_| \___/|_| |_|\__,_|\__,_|\__|
Debugger listening on ws://127.0.0.1:9229/vSOlrj5WsknK3-vm0AU4c8QqaxZpMn9rQSwuS16nb_k
For help, see: https://www.graalvm.org/tools/chrome-debugger
E.g. in Chrome open: devtools://devtools/bundled/js_app.html?ws=127.0.0.1:9229/vSOlrj5WsknK3-vm0AU4c8QqaxZpMn9rQSwuS16nb_k
```
--------------------------------
### Generate Gradle Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Use this command to create a new Gradle Java application project. This is an alternative to the Maven project setup for GraalPy integration.
```shell
gradle init --type java-application --dsl kotlin --test-framework junit-jupiter \
--package org.example --project-name example --java-version 17 \
--no-split-project --no-incubating
```
--------------------------------
### Setup File Comparison with Python Script
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-scripts-debug-guide/README.md
This Java code sets up a drag-and-drop handler to compare two files using an embedded Python script. It evaluates the Python script, retrieves the 'compare_files' function, and executes it with file paths, displaying the result.
```java
private void setupFileComparison(final Text target) {
try {
context.eval(Source.newBuilder("python", App.class.getResource("/compare_files.py")).build()); // ①
} catch (IOException e) {
throw new RuntimeException(e);
}
final Value compareFiles = context.getBindings("python").getMember("compare_files"); // ②
target.setOnDragDropped((event) -> {
boolean success = false;
List files;
if ((files = event.getDragboard().getFiles()) != null && files.size() == 2) {
try {
File file0 = files.get(0), file1 = files.get(1);
double result = compareFiles.execute(file0.getAbsolutePath(), file1.getAbsolutePath()).asDouble(); // ③
target.setText(String.format("%s = %f x %s", file0.getName(), result, file1.getName()));
success = true;
} catch (RuntimeException e) {
target.setText(e.getMessage());
}
}
resetTargetColor(target);
event.setDropCompleted(success);
event.consume();
});
}
```
--------------------------------
### Build the Demo Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/espresso/espresso-continuations/README.md
Builds the Java demo application using Maven.
```bash
./mvnw package
```
--------------------------------
### Execute Main Application with Continuations
Source: https://github.com/graalvm/graal-languages-demos/blob/main/espresso/espresso-continuations/README.md
Executes the main method of the demo application, enabling Espresso Continuations.
```bash
$JAVA_HOME/bin/java --experimental-options --java.Continuum=true \
-jar target/demo-1.0-SNAPSHOT-jar-with-dependencies.jar
```
--------------------------------
### Run Application with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-starter/README.md
Builds and tests the demo application using Gradle. Use this command to execute the main method.
```bash
./gradlew test
```
```bash
./gradlew run
```
--------------------------------
### Run Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-starter/README.md
Builds and tests the demo application using Maven. Use this command to execute the main method.
```bash
./mvnw test
```
```bash
./mvnw exec:exec
```
--------------------------------
### Build and Test with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-starter/README.md
Builds and tests the demo application using Gradle wrapper.
```bash
./gradlew test
```
--------------------------------
### Build and Test with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-starter/README.md
Builds and tests the demo application using Maven wrapper.
```bash
./mvnw test
```
--------------------------------
### Execute Main Method with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-starter/README.md
Executes the main method of the demo application using Gradle wrapper.
```bash
./gradlew run
```
--------------------------------
### Run Application with Gradle (Execute)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-openai-starter/README.md
Executes the main method of the demo application using Gradle, passing user input as an argument. Requires OPENAI_API_KEY to be set.
```bash
./gradlew run --args="'How can I check if my code runs on GraalPy?'"
```
--------------------------------
### Run Application with Maven (Execute)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-openai-starter/README.md
Executes the main method of the demo application using Maven, passing user input as an argument. Requires OPENAI_API_KEY to be set.
```bash
./mvnw exec:exec -Duser.input="'How can I check if my code runs on GraalPy?'"
```
--------------------------------
### Freeze Dependencies (macOS/Linux - Gradle)
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Lists installed Python packages in the virtual environment for Gradle projects on macOS and Linux.
```shell
./app/build/generated/graalpy/resources/org.graalvm.python.vfs/venv/bin/pip3 freeze -l
```
--------------------------------
### Configure GraalPy Packages in Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Configure the graalPy extension in build.gradle.kts to specify Python packages for installation. Requirement specifiers can be used.
```kotlin
graalPy {
packages = setOf("vaderSentiment==3.3.2") // ①
}
```
--------------------------------
### Clone Repository and Navigate
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-spring-boot-d3/README.md
Clone the graal-languages-demos repository and change the directory to the graaljs/graaljs-spring-boot-d3 project.
```bash
git clone https://github.com/graalvm/graal-languages-demos.git
cd graaljs/graaljs-spring-boot-d3
```
--------------------------------
### Build and Run Go Application with Maven Wrapper
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Utilize the Maven wrapper to package and run the application, specifying profiles for either the Go compiler or TinyGo. Ensure Go and TinyGo environments are exported.
```shell
# Make Go compiler and TinyGo available
export GOROOT=$(go env GOROOT)
export TINYGOROOT=$(tinygo env TINYGOROOT)
# Package the application using Go compiler
./mvnw -Pgo package
# Run the application
./mvnw exec:exec
# or package the application using TinyGo
./mvnw -Ptinygo package
# Run the application
./mvnw exec:exec
```
--------------------------------
### EchoInputCallback Java Implementation
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-jython-guide/README.md
A simple Java class implementing the InputCallback interface for echoing input strings. It requires no setup or teardown for the interpreter.
```java
package org.example;
final class EchoInputCallback implements InputCallback {
@Override
public void setUp(Workspace workspace) {
}
@Override
public String interpret(String code) {
return code;
}
@Override
public void tearDown() {
}
}
```
--------------------------------
### Run Demo with Debug Adapter Protocol Enabled
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-spring-boot-photon/README.md
Execute the demo application with the Debug Adapter Protocol enabled to initiate a debugging session. This allows for breakpoints and stepping through Rust code.
```bash
./target/demo-wasm-debug -Ddap=true
```
--------------------------------
### Build and Execute Java Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-c-code-guide/README.md
Commands to package the Java application and execute it using Maven. Assumes a Maven project structure with the necessary configurations.
```shell
./mvnw package
./mvnw exec:exec
```
--------------------------------
### Execute Main Method with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-starter/README.md
Executes the main method of the demo application using Maven wrapper.
```bash
./mvnw exec:java
```
--------------------------------
### Generate Native Executable with Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-micronaut-guide/README.md
Use this command to compile your Micronaut application into a native executable using Gradle. Ensure JAVA_HOME is set to a GraalVM installation.
```bash
./gradlew nativeCompile
./build/native/nativeCompile/demo
```
--------------------------------
### Generate Native Executable with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-micronaut-guide/README.md
Use this command to package your Micronaut application as a native executable using Maven. Ensure JAVA_HOME is set to a GraalVM installation.
```bash
./mvnw package -Dpackaging=native-image
./target/graalpy-micronaut
```
--------------------------------
### Configure GraalPy Maven Plugin for Packages
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-freeze-dependencies-guide/README.md
Configure the graalpy-maven-plugin in your pom.xml to specify Python packages to be installed. Packages are embedded as standard Java resources by default.
```xml
org.graalvm.python
graalpy-maven-plugin
25.0.3
vaderSentiment==3.3.2
process-graalpy-resources
```
--------------------------------
### Compiling and Running the Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-jython-guide/README.md
Commands to compile and run the Java application using Maven wrapper. This allows for testing the Jython to GraalPy migration.
```shell
./mvnw compile
./mvnw exec:java -Dexec.mainClass=org.example.App
```
--------------------------------
### Build and Run Spring Boot Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-spring-boot-d3/README.md
Build and run the Spring Boot application using the provided Maven wrapper script.
```bash
./mvnw spring-boot:run
```
--------------------------------
### Create GraalPy Virtual Environment
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Creates a new virtual environment named 'myvenv' using the GraalPy standalone distribution. This isolates Python package installations.
```shell
> {path/to/graalpy-standalone}/bin/graalpy -m venv myvenv
```
--------------------------------
### GraalJS Entry Point with TextEncoder Polyfill
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Sets up the main entry point for the GraalJS bundle, importing a TextEncoder polyfill and re-exporting the qrcode module.
```javascript
// GraalJS doesn't have built-in TextEncoder support yet. It's easy to import it from a polyfill in the meantime.
import 'fast-text-encoding';
// Re-export the "qrcode" module as a "QRCode" object in the exports of the bundle.
export * as QRCode from 'qrcode';
```
--------------------------------
### Create Go Project Directory
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Creates a directory structure for the Go project within the Maven project.
```bash
mkdir src/main/go/
touch src/main/go/main.go
```
--------------------------------
### Run Maven Tests
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-spring-boot-photon/README.md
Execute the integration tests for the demo application using Maven. This verifies that applying effects to images yields consistent results.
```bash
./mvnw test
```
--------------------------------
### Maven Build and Run Commands
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Commands to build the Java application using Maven and then execute it with a specific main class and arguments.
```shell
mvn package
mvn exec:java -Dexec.mainClass=com.example.App -Dexec.args="https://www.graalvm.org/"
```
--------------------------------
### Configure Python Packages in Gradle
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-javase-guide/README.md
Define Python packages and their versions using the GraalPy Gradle plugin. This setup integrates package management directly into the Gradle build process.
```kotlin
plugins {
application
id("org.graalvm.python") version "25.0.3"
}
graalPy {
packages = setOf("qrcode==7.4.2")
externalDirectory = file("${project.projectDir}/python-resources")
}
```
--------------------------------
### Embed and Use Go WebAssembly Module from Java
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Demonstrates embedding a Go WebAssembly module in a Java application, setting up the GraalVM context, and interacting with the Wasm module via a Java interface.
```java
package com.example;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.graalvm.polyglot.PolyglotAccess;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class App {
public static final String GO_MAIN_WASM = "/go/main.wasm";
public static final String GO_WASM_EXEC = "/go/wasm_exec.js";
public static void main(String[] args) throws IOException {
// Load Go resources
byte[] wasmBytes;
try (InputStream in = App.class.getResourceAsStream(GO_MAIN_WASM)) {
if (in == null) {
throw new FileNotFoundException(GO_MAIN_WASM);
}
wasmBytes = in.readAllBytes();
}
URL wasmExecURL = App.class.getResource(GO_WASM_EXEC);
if (wasmExecURL == null) {
throw new FileNotFoundException(GO_WASM_EXEC);
}
// Create a context with Wasm and JavaScript access
try (Context context = Context.newBuilder("js", "wasm")
.option("js.global-property", "true") // experimental
.option("js.performance", "true") // experimental
.option("js.text-encoding", "true")
.option("js.webassembly", "true")
.allowExperimentalOptions(true)
.allowHostAccess(HostAccess.ALL)
.allowPolyglotAccess(PolyglotAccess.ALL)
.build()) {
// Install Wasm bytes and crypto polyfill in JS binding
Value jsBindings = context.getBindings("js");
jsBindings.putMember("wasmBytes", wasmBytes);
jsBindings.putMember("crypto", new CryptoPolyfill());
// Evaluate wasm_exec.js file
context.eval(Source.newBuilder("js", wasmExecURL).build());
// Instantiate the Wasm module and invoke go.run()
context.eval("js", """
async function run(wasmBytes) {
const go = new Go();
const {instance} = await WebAssembly.instantiate(new Uint8Array(wasmBytes), go.importObject);
go.run(instance);
}
run(wasmBytes);
""");
// Access main package and interact with it through a Java interface
MyGoPackage myGoPackage = jsBindings.getMember("main").as(MyGoPackage.class);
System.out.println(myGoPackage.compilerAndVersion());
System.out.printf("3 + 4 = %d%n", myGoPackage.add(3, 4));
System.out.printf("reverseString('Hello World') = %s%n", myGoPackage.reverseString("Hello World"));
}
}
}
```
--------------------------------
### Micronaut Application Run Commands
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-micronaut-multithreaded/README.md
Commands to run the Micronaut application using Maven or Gradle. These commands start the application on port 8080, allowing for testing of the CSV analysis endpoint.
```bash
./mvnw mn:run
```
```bash
./gradlew run
```
--------------------------------
### Copy wasm_exec.js for TinyGo
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Use the `maven-resources-plugin` to copy the `wasm_exec.js` file from TinyGo's installation directory to the target output directory. This is required for running Go WebAssembly modules compiled with TinyGo.
```xml
maven-resources-plugin
copy-extra-resources
process-resources
copy-resources
${project.build.outputDirectory}/go
${env.TINYGOROOT}/targets
wasm_exec.js
```
--------------------------------
### Execute Application with Kryo Serializer
Source: https://github.com/graalvm/graal-languages-demos/blob/main/espresso/espresso-continuations/README.md
Executes the demo application using Kryo as the serialization method for continuations.
```bash
$JAVA_HOME/bin/java --experimental-options --java.Continuum=true \
-jar target/demo-1.0-SNAPSHOT-jar-with-dependencies.jar -s kryo
```
--------------------------------
### Copy wasm_exec.js for Official Go Compiler
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Use the `maven-resources-plugin` to copy the `wasm_exec.js` file from the Go toolchain's installation directory to the target output directory. This is required for running Go WebAssembly modules.
```xml
maven-resources-plugin
copy-extra-resources
process-resources
copy-resources
${project.build.outputDirectory}/go
${env.GOROOT}/lib/wasm
wasm_exec.js
```
--------------------------------
### Java Application to Generate and Display QR Code
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-javase-guide/README.md
An example Java application that uses GraalPy to generate a QR code from a string and display it in a Swing JFrame. It requires the 'graalpy.resources' system property to be set.
```java
package org.example;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class App {
public static void main(String[] args) throws IOException {
String path = System.getProperty("graalpy.resources");
if (path == null || path.isBlank() || path.equals("null")) {
System.err.println("Please provide 'graalpy.resources' system property.");
System.exit(1);
}
try (var context = GraalPy.createPythonContext(path)) { // ①
QRCode qrCode = context.eval("python", "import qrcode; qrcode").as(QRCode.class); // ②
IO io = context.eval("python", "import io; io").as(IO.class);
IO.BytesIO bytesIO = io.BytesIO(); // ③
qrCode.make("Hello from GraalPy on JDK " + System.getProperty("java.version")).save(bytesIO);
var qrImage = ImageIO.read(new ByteArrayInputStream(bytesIO.getvalue().toByteArray())); // ④
JFrame frame = new JFrame("QR Code");
frame.getContentPane().add(new JLabel(new ImageIcon(qrImage)));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
}
```
--------------------------------
### Compile Go to WASM with TinyGo
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Use the `exec-maven-plugin` to invoke TinyGo for building WebAssembly modules. Ensure `TINYGOROOT` is set and TinyGo is in your PATH.
```xml
org.codehaus.mojo
exec-maven-plugin
3.1.0
build-go-wasm
generate-resources
exec
${env.TINYGOROOT}/bin/tinygo
js
wasm
build
-o
${project.build.outputDirectory}/go/main.wasm
src/main/go/main.go
```
--------------------------------
### Gradle Build and Run Commands
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Commands to build the Java application using Gradle and then run it with a specific argument.
```shell
./gradlew build
./gradlew run --args="https://www.graalvm.org/"
```
--------------------------------
### Spring Service for Sentiment Analysis with GraalPy
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-spring-boot-guide/README.md
A Spring service that integrates with GraalPy to perform sentiment analysis. It initializes a Python sentiment analyzer and exposes a method to get sentiment scores for given text.
```java
package com.example.demo;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
@ImportRuntimeHints(SentimentAnalysisService.SentimentIntensityAnalyzerRuntimeHints.class)
public class SentimentAnalysisService {
private final SentimentIntensityAnalyzer sentimentIntensityAnalyzer;
public SentimentAnalysisService(GraalPyContext context) {
var value = context.eval("""
from vader_sentiment.vader_sentiment import SentimentIntensityAnalyzer
SentimentIntensityAnalyzer() # ①
""");
sentimentIntensityAnalyzer = value.as(SentimentIntensityAnalyzer.class); // ②
}
public Map getSentimentScore(String text) {
return sentimentIntensityAnalyzer.polarity_scores(text); // ③
}
static class SentimentIntensityAnalyzerRuntimeHints implements RuntimeHintsRegistrar { // ④
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.proxies().registerJdkProxy(SentimentIntensityAnalyzer.class);
}
}
}
```
--------------------------------
### Java App with GraalPy Custom Virtual Environment
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Configures a GraalPy Context to use a specified Python virtual environment, allowing access to its installed packages. This is useful for isolating Python dependencies for your embedded application.
```java
package org.example;
import org.graalvm.polyglot.*;
import org.graalvm.polyglot.io.*;
import java.nio.file.*;
public class App {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
public static void main(String[] args) {
if (System.getProperty("venv") == null) {
System.err.println("Provide 'venv' system property.");
System.exit(1);
}
Path executable;
if (IS_WINDOWS) { // ①
executable = Paths.get(System.getProperty("venv"), "Scripts", "python.exe");
} else {
executable = Paths.get(System.getProperty("venv"), "bin", "python");
}
try (Context context = Context.newBuilder() // ②
.option("python.Executable", executable.toAbsolutePath().toString()) // ③
.option("python.ForceImportSite", "true") // ④
.allowIO(IOAccess.newBuilder().allowHostFileAccess(true).build()) // ⑤
.build()) {
Value asciiArt = context.eval("python", "import art; art.text2art('GraalPy')"); // ⑥
System.out.println(asciiArt.asString()); // ⑦
}
}
}
```
--------------------------------
### Compile Go to WASM with Official Go Compiler
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-go-code-guide/README.md
Use the `exec-maven-plugin` to invoke the official Go compiler for building WebAssembly modules. Ensure `GOROOT` is set and the Go compiler is in your PATH.
```xml
org.codehaus.mojo
exec-maven-plugin
3.1.0
build-go-wasm
generate-resources
exec
${env.GOROOT}/bin/go
js
wasm
build
-o
${project.build.outputDirectory}/go/main.wasm
src/main/go/main.go
```
--------------------------------
### Create JavaScript Source Directory
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graaljs/graaljs-webpack-guide/README.md
Creates the directory for your JavaScript sources and navigates into it.
```shell
mkdir -p src/main/js
cd src/main/js
```
--------------------------------
### Java Code for GraalPy Integration
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-native-extensions-guide/README.md
Integrate Java code with GraalPy to execute Python functions. This example demonstrates setting up a GraalPy context, passing Java data to Python, and calling a Python function from Java.
```java
package org.example;
import org.graalvm.polyglot.*;
import org.graalvm.python.embedding.GraalPyResources;
import java.util.Set;
public class App {
private static final Set FRUITS = Set.of(
"apple", "banana", "peach", "grape", "orange",
"pear", "mango", "pineapple", "lemon", "lime", "apricot");
public static void main(String[] args) {
try (Context context = GraalPyResources.createContext()) {
Value pythonBindings = context.getBindings("python");
pythonBindings.putMember("fruits", FRUITS.toArray());
context.eval("python", """
import polyleven
def get_similar_word(value):
words = [x for x in fruits if polyleven.levenshtein(x, value) <= 1]
return words[0] if words else None
""");
Value getSimilarWord = pythonBindings.getMember("get_similar_word");
for (String value : args) {
if (FRUITS.contains(value)) {
System.out.printf("✅ %s%n", value);
} else {
System.out.printf("❌ %s", value);
Value similarWord = getSimilarWord.execute(value);
if (!similarWord.isNull()) {
System.out.printf(" (did you mean '%s')%n", similarWord.asString());
} else {
System.out.println();
}
}
}
}
}
}
```
--------------------------------
### Sentiment Analysis Controller Test
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-micronaut-guide/README.md
Tests the sentiment analysis endpoint by making GET requests to /analyze with different text inputs. It verifies that the compound score is within the expected range for positive and negative inputs.
```java
package org.example;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;
@MicronautTest // ①
class SentimentAnalysisControllerTest {
@Test
void testAnalyzeResponse(@Client("/") HttpClient client) { // ②
Map response = client.toBlocking().retrieve("/analyze?text=happy", Map.class); // ③
assertTrue(response.get("compound") > 0.1);
response = client.toBlocking().retrieve("/analyze?text=sad", Map.class);
assertTrue(response.get("compound") < -0.1);
}
}
```
--------------------------------
### Run Spring Boot Application
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-spring-boot-pygal-charts/README.md
Packages and runs the Spring Boot demo application using Maven wrapper. Access the application via browser URLs to view charts.
```bash
./mvnw package spring-boot:run
```
--------------------------------
### GraalPy Setup with Polyglot API
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-jython-guide/README.md
Initializes a GraalPy context for embedding Python code. It configures the engine, allows all access, and enables Jython emulation heuristics. The workspace object is made available to the Python global scope via bindings.
```java
package org.example;
import org.graalvm.polyglot.*;
final class GraalPyInputCallback implements InputCallback {
static Source GRAALPY_CODE = Source.create("python", "__import__('sys').version");
static Engine engine = Engine.create("python");
private Context python;
@Override
public void setUp(Workspace workspace) {
this.python = Context.newBuilder("python") // ①
.engine(engine) // ②
.allowAllAccess(true).option("python.EmulateJython", "true") // ③
.build();
python.getBindings("python").putMember("this", workspace); // ④
}
}
```
--------------------------------
### Create Rust Library Project
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalwasm/graalwasm-embed-rust-code-guide/README.md
Initializes a new Rust library project using Cargo. This command creates the necessary directory structure and basic configuration files for the Rust library.
```bash
cargo new --lib src/main/rust/mywasmlib
```
--------------------------------
### Compile and Run GraalPy Application with Maven
Source: https://github.com/graalvm/graal-languages-demos/blob/main/graalpy/graalpy-custom-venv-guide/README.md
Commands to compile the Java application using Maven and then execute it, specifying the path to the Python virtual environment via the -Dvenv system property.
```shell
./mvnw compile
./mvnw exec:java -Dexec.mainClass=org.example.App -Dvenv=/path/to/myvenv
```