How to load .js files into a Rhino context in Java
Asked Answered
S

1

10

Here is my situation:

I have access to a Rhino Context object in a Java class. I want to read in a bunch of .js files and pass them along to the Rhino context to have them evaluated. I'm not really interested in having the functions in the .js files available in the scripting context so much as I am in just having the variables that are declared in the .js files available (this is a tooling validation kind of issue).

Ideally I would read in and try to evaluate each file all at once, not line by line. I noticed there is a method in Context (see Rhino API) called evaluateReader(). My first guess is I should get all the files I want to load, go through them all, and call this method passing in some kind of reader object for each one, and great, now they're all in my scripting context.

So, assuming that I am on the right track there, can anyone tell me if there are any good practices to follow for using .js files in Java scripting contexts, or if there is a better way of doing it, or you did it some other way, etc?

Not looking for implementation details here, just feedback from other people that might have done this already in some of their code. Messing with scripting languages from Java is new to me.

Sherlene answered 19/5, 2009 at 1:5 Comment(0)
V
13

Are you aware that Rhino ships in Java 6?

String javaScriptExpression = "sayHello(name);";
Reader javaScriptFile = new StringReader(
    "function sayHello(name) {\n"
        + "    println('Hello, '+name+'!');\n" + "}");

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory
    .getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setAttribute("name", "JavaScript",
    ScriptContext.ENGINE_SCOPE);

engine.eval(javaScriptFile);
engine.eval(javaScriptExpression);

If you want to use it with Java 5, you'll have to download the API separately. You can get engines for many popular scripting languages from scripting.dev.java.net.

Villon answered 19/5, 2009 at 7:26 Comment(3)
"You can get engines for many popular scripting languages from scripting.dev.java.net." No, we can't anymore. I know this is extremely old, but is there a newer link we should use?Parra
@hexafraction Try this question: #11838869Villon
+1 Thanks, that and the web archive have helped, since the latter is just a bag of links, really.Parra

© 2022 - 2024 — McMap. All rights reserved.