Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. In main/java/com/mycompany/app, add a new file named PolyglotSample.java with the following code:

    Code Block
    languagejava
    titlePolyglotSample.java
    linenumberstrue
    collapsetrue
    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);
            }
        }
    }  


  2. Create the following structure to store the JS source file, so that Java can find it, within the main folder: resources/com/mycompany/app
  3. In this resources/com/mycompany/app folder, create a file named fib.js and paste in the following JS code:

    Code Block
    languagejs
    titlefib.js
    linenumberstrue
    collapsetrue
    (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;
    })


  4. Save all files and invoke action from Command Palette: Java: Compile Workspace.

    Note:
    • This is an action provided by VSNetBeans which builds the project.
    • The project is also built when the debugger starts, but it is worth checking before the first debug session to make sure that the Maven build passes.

Once the build succeeds, let's test the project.

Testing
  1. Set breakpoint to line 11 in fib.js and
  2. Select F5 to launch debugger and select type Java 8+ which is VSNetBeans provided debugger for JDK 8 and Polyglot capable of debugging Java and scripting languages like Graal.JS impl. of JS.
  3. When started you should see something like following screenshot with Call Stack from JS to Java and variables from JS and Java depending on what context you have  currently stepped into.

...