Subj : Re: Calling a compiled script with arguments To : redcoat From : Igor Bukanov Date : Thu Dec 16 2004 12:09 pm This is a multi-part message in MIME format. --------------030704060708010206080607 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit redcoat wrote: > Hi, > > I need to have a compiled script in a file that I can run and pass > arguments to. Use Context.compileString|Context.compileReader to get a compiled Script object that you can execute several times against different scopes with different host objects. The attached ScriptTest.java gives an example how to do this. If you compile and execute it like: java ScriptTest test.js where test.js contains: function print(str) { java.lang.System.out.println(str); } print("**** START OF SCRIPT EXECUTION ****"); print("arg1="+arg1); print("arg2="+arg2); print(""); Then you would get on the console something like the following: **** START OF SCRIPT EXECUTION **** arg1=0 arg2=Thu Dec 16 12:04:29 CET 2004 **** START OF SCRIPT EXECUTION **** arg1=1 arg2=Thu Dec 16 12:04:29 CET 2004 **** START OF SCRIPT EXECUTION **** arg1=2 arg2=Thu Dec 16 12:04:29 CET 2004 Regards, Igor --------------030704060708010206080607 Content-Type: text/x-java; name="ScriptTest.java" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="ScriptTest.java" import java.io.*; import java.util.*; import org.mozilla.javascript.*; public class ScriptTest { public static void main(String[] args) throws Exception { String fileName = args[0]; Script script = compileScript(fileName); Scriptable sharedLibraryScope = prepareSharedScope(); for (int i = 0; i != 3; ++i) { Scriptable scope = prepareExecScope(sharedLibraryScope, new Integer(i), new Date().toString()); execScript(script, scope); } } static Script compileScript(String fileName) throws IOException { FileReader r = new FileReader(fileName); try { Context cx = Context.enter(); try { return cx.compileReader(r, fileName, 1, null); } finally { Context.exit(); } } finally { r.close(); } } static Scriptable prepareSharedScope() { Context cx = Context.enter(); try { Scriptable sharedScope = cx.initStandardObjects(); return sharedScope; } finally { Context.exit(); } } /** * Prepare scope for script execution with arg1 and arg2 * exposed as arg1 and arg2 variables. */ static Scriptable prepareExecScope(Scriptable sharedScope, Object arg1, Object arg2) { Context cx = Context.enter(); try { Scriptable scope = cx.newObject(sharedScope); scope.setPrototype(sharedScope); scope.setParentScope(null); ScriptableObject.putProperty( scope, "arg1", Context.javaToJS(arg1, scope)); ScriptableObject.putProperty( scope, "arg2", Context.javaToJS(arg2, scope)); return scope; } finally { Context.exit(); } } static void execScript(Script script, Scriptable scope) { Context cx = Context.enter(); try { script.exec(cx, scope); } finally { Context.exit(); } } } --------------030704060708010206080607-- .