10

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.

Michael Yousef
  • 602
  • 3
  • 11
  • 22
  • You can perhaps start from [here](http://download.java.net/jdk8/docs/technotes/guides/scripting/) <-- Click – Rohit Jain Mar 25 '14 at 19:29
  • 5
    the difference between java and javascript is like the difference between apple and pineapple. the only thing they have in common is the 'java' in the name. aside of both being programming languages. – Banana Mar 25 '14 at 19:31
  • 8
    a guy named Banana with fruit analogies, hilarious – j.con Mar 25 '14 at 19:36
  • 1
    @SotiriosDelimanolis I didn't mean the difference between the two, I want to delegate some part of a large Java project to JavaScript, in which I will use Nashorn. It's new and I've never used it before, so I wanted to learn. I know it requires javax.script and I'm unfamiliar with how it works. There are several things like hooking into the Java code that I need to learn – Michael Yousef Mar 25 '14 at 19:58
  • That clarifies it. Add those details to your question. – Sotirios Delimanolis Mar 25 '14 at 20:00
  • @RohitJain Thanks that looks good and hopefully answers many of my questions. – Michael Yousef Mar 25 '14 at 20:03
  • A good way to get started is to fire up `jjs` and start experimenting. This is much easier than going through the JSR-223 APIs. – Seth Tisue Mar 26 '14 at 17:03

4 Answers4

17

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.

Ben
  • 271
  • 1
  • 9
11

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

Community
  • 1
  • 1
Vik Gamov
  • 5,446
  • 1
  • 26
  • 46
2

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;
    }

}
Kong
  • 8,792
  • 15
  • 68
  • 98
2

Here is a nice, very basic "getting started" video:

https://www.youtube.com/watch?v=Cxyg22C5gcw

Julien Ponge has also written a good introductory article:

http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html

I would also recommend the Nashorn Wiki for the formal documentation:

https://wiki.openjdk.java.net/display/Nashorn/Main

Marcus
  • 141
  • 7