...
Scenario 2: Polyglot Debugging
Please install Apache NetBeans Language Server extension (VSNetBeans). Use Install from VSIX command. Once released it will be available from VSCode Marketplace for direct installation
In this sample we will go over how to create and debug Java <> JavaScript polyglot project using JDK 11, Graal.JS, and ready to go go sample:
graal-js-jdk11-maven-demo Maven Archetype. Sample
The sample is a simple Java application invoking in a loop fibonaci calculation for incremented number written in JavaScript.
Complete sample is attached below for your convenience as well.
Set Up
- Clone sample repository and move to the newly cloned directory.
- Make sure that
JAVA_HOME
points at a JDK11export JAVA_HOME=/path/to/jdk11.
- Open VSCode with VSNetBeans installed.
- Go to File | Preferences and search for
netbeans.jdkhome
and set it to/path/to/jdk11.
- Open Folder with
graal-js-jdk11-maven-demo
in in VSCode. - Remove
App.java
andAppTest.java
originally coming with the sample Maven project.
Development
Into
main/java/com/mycompany/app
, add new File file namedPolyglotSample.java
with the following code:Code Block language java title PolyglotSample.java linenumbers true collapse true package com.mycompany.app; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import org.graalvm.polyglot.Value; import java.net.URL; public class PolyglotSample { public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException { Context ctx = Context.create(); URL fibUrl = PolyglotSample.class.getResource("fib.js"); Source fibSrc = Source.newBuilder("js", fibUrl).build(); Value fib = ctx.eval(fibSrc); for (int i = 0; i < 10; i++) { Value res = fib.execute(i); System.out.println("Polyglot with Graal.JS - fib(" + i + ") = " + res.asInt()); Thread.sleep(500); } } }
- Then in In terminal or file explorer, create the following structure where to store the JS source file so that Java can find it, it has to be under within the
main
folder:resources/com/mycompany/app
- Inside this
resources/com/mycompany/app
create file namedfib.js
and paste in following JS code:Code Block language js title fib.js linenumbers true collapse true (function(n) { function fib(x) { if (x <= 2) { return 1; } let fibX1 = fib(x - 1); let fibX2 = fib(x - 2); return fibX1 + fibX2; } let fibN = fib(n); print(`JavaScript computed that fib(${n}) is ${fibN}`); return fibN; })
- Save all files and invoke action from Command Palette: Java: Compile Workspace
- this is the action provided by VSNetBeans which builds the project.
- Project is normally built also when debugger start but it is worth for the 1st time see if maven build passes.
...