Embed Avatar JS in Java Application Example

1k views Asked by At

Using Java 8, I'd like to programmatically load a javascript file and execute it using Avatar JS (for Node env support). I also want to use Maven to manage the dependencies.

Here's the simple Nashorn snippet I'm using and I'd like to extend this to support Node.JS modules, ideally using Avatar JS.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
InputStream in = getClass().getClassLoader().getResourceAsStream("js/hello-world.js");
String result = (String)engine.eval(new InputStreamReader(in));
System.out.print(result);

The relevant Maven config also looks like this:

<repositories>
    <repository>
        <id>nexus-snapshots</id>
        <name>Nexus Snapshots</name>
        <url>https://maven.java.net/content/repositories/snapshots/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>avatar-js</artifactId>
        <version>0.10.32-SNAPSHOT</version>
    </dependency>

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>libavatar-js-linux-x64</artifactId>
        <version>0.10.32-SNAPSHOT</version>
        <type>pom</type>
    </dependency>
</dependencies>

I get the impression there's a lot of good functionality in Avatar, but I'm struggling to find any decent docs or examples. Can anyone provide a code example of how to do this?

1

There are 1 answers

0
Phil Mander On BEST ANSWER

I figured this out, the relevant code I have running looks like this:

import com.oracle.avatar.js.Server;
import com.oracle.avatar.js.Loader;
import com.oracle.avatar.js.log.Logging;

and

String runJs() throws Throwable {

    StringWriter scriptWriter = new StringWriter();
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    ScriptContext scriptContext = engine.getContext();
    scriptContext.setWriter(scriptWriter);
    Server server = new Server(engine, new Loader.Core(), new Logging(false), System.getProperty("user.dir"));
    server.run("js/hello-world.js");

    return scriptWriter.toString();
}

and, for now, a simple hello-world.js:

var util = require('util')
var result = util.format('hello %s', 'Phil');
print(result);

I also pass in java.library.home as a JVM argument when running the application. The Avatar native library resides in this directory