Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to scripting with Java and Nashorn, any tutorials? [closed]

Are there any good tutorials or the likes for getting stated with this? I have yet to do any scripting in Java, though I am familiar with JavaScript already. Thanks. Essentially, I want to use JavaScript/XML to handle part of my project. I know Java 8 introduced JavaScript support via Nashorn. I want to learn how this works. I know it involves using javax.script, but I don't know how that package works nor do I understand how Nashorn works.

like image 694
Michael Yousef Avatar asked Mar 25 '14 19:03

Michael Yousef


3 Answers

I played a lot with nashorn in the last couple of weeks. I wrote all my findings in an example-driven tutorial:

http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

It covers the following topics:

  • calling javascript functions from java code
  • calling java methods from javascript
  • using java classes from within javascript
  • summary of all language extensions (e.g. for each)

I hope it's helpful for you to start with Nashorn.

like image 101
Ben Avatar answered Oct 30 '22 12:10

Ben


Recently, I did couple presentations on Java and JavaScript (via Nashorn). You can find my slides and examples here.

Here is a very simple script runner implementation

import javax.script.*;

public class ScriptRunner {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        String scriptName = args[0];
        Bindings bindings = nashorn.createBindings();
        bindings.put("scriptFileName", scriptName);
        nashorn.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        nashorn.eval("load('src/main/resources/javascript/' + scriptFileName)");
    }

}

test.js that you can pass as an application parameter.

print("This is hello from test.js");

Also, there is a tool jjs that comes with JDK8. It's CLI JavaScript interpreter. It can be used to write shell scripts in JavaScript and Java. (Good SO advice how to improve jjs on osx, linux). Here is an example of such script

#!/usr/local/bin/jjs -scripting

var currentDir = new java.io.File('.'),
    allFiles = currentDir.list();
print(currentDir.getCanonicalPath());
for (var i = 0; i < allFiles.length; i++) {
    print(allFiles[i]);
}

Feel free to ask question if you have any.

Thanks,

Vik

like image 11
Vik Gamov Avatar answered Oct 30 '22 11:10

Vik Gamov


Nashorn is accessed through the standard Java JSR 223 scripting APIs.

A good generic example is here:

http://www.drdobbs.com/jvm/jsr-223-scripting-for-the-java-platform/215801163

Nashorn specific guidance is here:

https://wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notes

Here's an example from my code loading static library scripts and building an Invocable custom function:

public class ScriptRunner {
    private static final Logger log = LoggerFactory.getLogger(ScriptRunner.class);
    private static final String ENGINE = "nashorn";
    private String functions;

    public ScriptRunner() throws IOException {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[]  resources = resolver.getResources("your/class/path/*.js");
        log.debug("Found {} script resources", resources.length);
        StringBuilder functions = new StringBuilder();
        for (Resource resource : resources) {
            functions.append(IOUtils.toString(resource.getInputStream()));
        }
        this.functions = functions.toString();
    }

    /**
     * Build an Invocable script.
     * @param script The function code.
     * @return Compiled, invocable script.
     */
    public Invocable buildInvocable(String script) throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName(ENGINE);
        engine.eval(functions);
        engine.eval(script);
        return (Invocable) engine;
    }

}
like image 2
Kong Avatar answered Oct 30 '22 11:10

Kong