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.
Trackbacks
[...] up where I left off in the previous post, I am going to cover some ways to get data into a [...]