Running a JavaScript file from Java

I gravitate towards writing testing infrastructure. I find it very rewarding to see my frameworks, abstractions and convenience APIs being used by my coworkers. As the testing gets further and further away from unit tests, having scripting capabilities tends to become increasingly important.

In the past, I’ve used BeanShell, jython and various DSLs to support test scripts. Recently, I’ve started using Java 6′s embedded ‘Rhino’ JavaScript engine.

In a series of posts, I want to share some basics of how you can enable cross-interactions between some Java code and some JavaScript.

I started with a basic script runner facade:

import javax.script.*;

public class ScriptRunner {
  private final ScriptEngineManager _manager;
  private final ScriptEngine _engine;

  public ScriptRunner() {
    _manager = new ScriptEngineManager();
    _engine = _manager.getEngineByName("JavaScript");
  }

  public Object run(String scriptName) throws ... {
    Reader reader = new InputStreamReader(getClass().getResourceAsStream(scriptName));
    return _engine.eval(reader);
  }
}

For simplicity, I placed this near-trivial script file in the classpath:

// hello_world.js
function myconcat(a, b) { return a + ' ' + b; }
myconcat('hello', 'world');

… and ran the script:

  public static void main(...) throws ... {
    ScriptRunner runner = new ScriptRunner();
    runner.run("hello_world.js");
  }

which produced the expected

hello world

No additional libraries, broadly and well understood script language… so a promising start.

Advertisement
Post a comment or leave a trackback: Trackback URL.

Trackbacks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.