views:

122

answers:

1

I want to run Protovis javascript from Java and get the evaluated SVG code. I am using javax.script.* to run the Javascript:

public static void EvalScript() throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    Object result = engine.eval("var vis = new pv.Panel().width(300).height(300)
        .add (pv.Line).data ([1,0.5, 0.1, 0.01, 0.001, 0.3, 0.2,0.1,1])
           .left (function () { return this.index * 30; })
           .bottom (function (d) { return d * 250; });
        vis.root.render();
        vis.scene[0].canvas.innerHTML;");         
    System.out.println(result);
}

This would complain because I never loaded Protovis itself, as would ordinarily be done with

<script type="text/javascript" src="../protovis-r3.1.0.js"></script> 

Is there a good way, short of sourcing in the full Javascript into the eval() command, of loading a library when running Javascript through javax.script?

+1  A: 

Well why would you not load the whole script in and hand it to eval()? If you want that Javascript execution context to parse and interpret the library, then something has to do that. You could of course supply a mechanism to the script context to let the script itself do the equivalent of the <script> tag example you gave, but it would end up being exactly the same thing.

I don't understand your comment about Rhino. The Javascript interpreter in JDK 1.6 is Rhino.

Pointy
Thanks. Not that I don't want to do this; just wondering if there is a better way rather than opening a FileReader and passing it to eval. I removed the Rhino comment. I just wanted to include that link for reference, although I know that it is Rhino.
Shane
OK, well cool then. The way I've done this in the past is to really provide both tricks: as a general service to the app, I'd "stuff" a couple of standard libraries into each Javascript environment. Then, I'd hook up a couple of APIs so that from the Javascript side, utility libraries could be loaded. (I was working in a web app, so the loading was always done through "getResourceAsStream", but loading from files or a PATH would be essentially the same.) Providing a Javascript-domain hook is nice if there are lots of libraries or little utility packages.
Pointy