/** * Utility method which dynamically binds a Context to the current thread, if none already exists. */ public static Object callMethod( ContextFactory factory, final Scriptable thisObj, final Function f, final Object[] args, final long argsToWrap) { if (f == null) { // See comments in getFunction return null; } if (factory == null) { factory = ContextFactory.getGlobal(); } final Scriptable scope = f.getParentScope(); if (argsToWrap == 0) { return Context.call(factory, f, scope, thisObj, args); } Context cx = Context.getCurrentContext(); if (cx != null) { return doCall(cx, scope, thisObj, f, args, argsToWrap); } else { return factory.call( new ContextAction() { public Object run(Context cx) { return doCall(cx, scope, thisObj, f, args, argsToWrap); } }); } }
void testWriteReadOnly(final boolean acceptWriteReadOnly) throws Exception { final Method readMethod = Foo.class.getMethod("getMyProp", null); final Foo foo = new Foo("hello"); foo.defineProperty("myProp", null, readMethod, null, ScriptableObject.EMPTY); final String script = "foo.myProp = 123; foo.myProp"; final ContextAction action = new ContextAction() { public Object run(final Context cx) { final ScriptableObject top = cx.initStandardObjects(); ScriptableObject.putProperty(top, "foo", foo); cx.evaluateString(top, script, "script", 0, null); return null; } }; final ContextFactory contextFactory = new ContextFactory() { @Override protected boolean hasFeature(final Context cx, final int featureIndex) { if (Context.FEATURE_STRICT_MODE == featureIndex) { return !acceptWriteReadOnly; } return super.hasFeature(cx, featureIndex); } }; contextFactory.call(action); }
public void Serialize(final Object obj) { ContextFactory factory = new JsContextFactory(); final GaeScriptableSerializer self = this; factory.call( new ContextAction() { @Override public Object run(Context cx) { Serialize((Scriptable) obj, obj, "/", 0); return null; } }); pr.flush(); }
public Rhino(final String dbname, final String fun) throws Exception { this.fun = fun; this.context = contextFactory.enterContext(); try { this.context.setClassShutter(SHUTTER); } catch (final SecurityException e) { // Thrown if already set and Rhino reassociates a previous context with this thread. } this.context.putThreadLocal("dbname", dbname); context.setOptimizationLevel(9); scope = context.initStandardObjects(); // compile user-defined function. this.userFun = context.compileFunction(scope, fun, "userFun", 0, null); // compile system function. this.systemFun = context.compileFunction( scope, "function(json, func) { var doc=JSON.parse(json); return func(doc); }", "systemFun", 0, null); ScriptableObject.defineClass(scope, RhinoDocument.class); // add JSON parser. context.evaluateString(scope, loadJSONParser(), "json2", 0, null); }
public <T> T runInsideContext(Class<T> clazz, JSRunnable<?> runnable) { rhinoContextFactory.enterContext(rhinoContext); try { return clazz.cast(runnable.run(rhinoContext)); } finally { Context.exit(); } }
public void readResourceIntoRhino(String resourceClasspath) throws IOException { Reader js = getResourceAsReader(resourceClasspath); rhinoContextFactory.enterContext(rhinoContext); try { rhinoContext.evaluateReader(rhinoScope, js, resourceClasspath, 1, null); } finally { Context.exit(); } }
public void readStringIntoRhino(String js, String sourceName) { LOG.fine(sourceName + ":\n" + js); rhinoContextFactory.enterContext(rhinoContext); try { rhinoContext.evaluateString(rhinoScope, js, sourceName, 1, null); } finally { Context.exit(); } }
@Before public void init() throws Exception { context = contextFactory.enterContext(); globalScope = context.initStandardObjects(); loadScript(TEST_ENVIRONMENT); loadScript(TEST_SETUP); loadScript(FILE_UNDER_TEST); }
public static Scriptable runScript(final Script script) { return (Scriptable) ContextFactory.getGlobal() .call( new ContextAction() { public Object run(Context cx) { ScriptableObject global = ScriptRuntime.getGlobal(cx); script.exec(cx, global); return global; } }); }
public Object invoke( ContextFactory cf, final Object target, final Scriptable topScope, final Method method, final Object[] args) { ContextAction action = new ContextAction() { public Object run(Context cx) { return invokeImpl(cx, target, topScope, method, args); } }; return cf.call(action); }
@NeedsContext private void doLint(final String javaScript) { contextFactory.call( new ContextAction() { public Object run(Context cx) { String src = javaScript == null ? "" : javaScript; Object[] args = new Object[] {src, optionsAsJavaScriptObject()}; Function lintFunc = (Function) scope.get("JSLINT", scope); // JSLINT actually returns a boolean, but we ignore it as we always go // and look at the errors in more detail. lintFunc.call(cx, scope, scope, args); return null; } }); }
private static Function<Object, String> compile(String function) { final ContextFactory contextFactory = ContextFactory.getGlobal(); final Context context = contextFactory.enterContext(); context.setOptimizationLevel(9); final ScriptableObject scope = context.initStandardObjects(); final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null); Context.exit(); return new Function<Object, String>() { public String apply(Object input) { // ideally we need a close() function to discard the context once it is not used anymore Context cx = Context.getCurrentContext(); if (cx == null) { cx = contextFactory.enterContext(); } final Object res = fn.call(cx, scope, scope, new Object[] {input}); return res != null ? Context.toString(res) : null; } }; }
public void input(Datum in) { Context c = ContextFactory.getGlobal().enterContext(); Object maybeFunc = _topLevel.get("handle", _topLevel); if (Scriptable.NOT_FOUND == maybeFunc || !(maybeFunc instanceof Function)) { // TODO better exception throw new RuntimeException("No handle function"); } Function func = (Function) maybeFunc; Object[] args = new Object[2]; args[0] = in; args[1] = _ops; Object result = func.call(c, _topLevel, _topLevel, args); // There's a couple of ways this interface could work: commit as a // side-effect, and commit as a return value. We use side-effect // for now, so the return value is ignored. }
public static Object eval(String source, Map<String, Scriptable> bindings) { Context cx = ContextFactory.getGlobal().enterContext(); try { Scriptable scope = cx.initStandardObjects(); if (bindings != null) { for (String id : bindings.keySet()) { Scriptable object = bindings.get(id); object.setParentScope(scope); scope.put(id, scope, object); } } return cx.evaluateString(scope, source, "source", 1, null); } finally { Context.exit(); } }
protected void parse() throws EvaluatorException { // Parse script source CompilerEnvirons ce = new CompilerEnvirons(); ScriptParserErrorReporter errorReporter = new ScriptParserErrorReporter(); ce.setGenerateDebugInfo(true); ce.initFromContext(ContextFactory.getGlobal().enterContext()); ce.setErrorReporter(errorReporter); Parser p = new Parser(ce, errorReporter); ScriptOrFnNode ast = p.parse(this.scriptSource, "script", 0); recursiveParse(ast); this.scriptParsed = true; }
JavaMembers(Scriptable scope, Class<?> cl, boolean includeProtected) { try { Context cx = ContextFactory.getGlobal().enterContext(); ClassShutter shutter = cx.getClassShutter(); if (shutter != null && !shutter.visibleToScripts(cl.getName())) { throw Context.reportRuntimeError1("msg.access.prohibited", cl.getName()); } this.includePrivate = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS); this.members = new HashMap<String, Object>(); this.staticMembers = new HashMap<String, Object>(); this.cl = cl; reflect(scope, includeProtected); } finally { Context.exit(); } }
@NeedsContext private String callReport(final boolean errorsOnly) { return (String) contextFactory.call( new ContextAction() { public Object run(Context cx) { Object[] args = new Object[] {Boolean.valueOf(errorsOnly)}; Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope); Object report = lintScope.get("report", lintScope); // Shouldn't happen ordinarily, but some of my tests don't have it. if (report == UniqueTag.NOT_FOUND) { return ""; } Function reportFunc = (Function) report; return reportFunc.call(cx, scope, scope, args); } }); }
/** * Turn the set of options into a JavaScript object, where the key is the name of the option and * the value is true. */ @NeedsContext private Scriptable optionsAsJavaScriptObject() { return (Scriptable) contextFactory.call( new ContextAction() { public Object run(Context cx) { applyDefaultOptions(); Scriptable opts = cx.newObject(scope); for (Entry<Option, Object> entry : options.entrySet()) { String key = entry.getKey().getLowerName(); // Use our "custom" version in order to get native arrays. Object value = Util.javaToJS(entry.getValue(), opts); opts.put(key, opts, value); } return opts; } }); }
public Scriptable initialState(Map<String, Object> zero) { Context context = ContextFactory.getGlobal().enterContext(); // Always interpret, since otherwise we have difficulty serialising. context.setOptimizationLevel(-1); // this arrangement means _global isn't mutable, and // variables go in _topLevel. ScriptableObject global = context.initStandardObjects(null, true); global.sealObject(); _global = global; _topLevel = context.newObject(_global); _topLevel.setPrototype(_global); _topLevel.setParentScope(null); // TODO complain if it's not there String script = zero.get("script").toString(); context.evaluateString(_topLevel, script, "<script>", 1, null); context.exit(); return _topLevel; }
public void initializeRhino() { rhinoContextFactory = new ContextFactory(); if (System.getProperty("cxf.jsdebug") != null && !rhinoDebuggerUp) { try { Class<?> debuggerMain = ClassLoaderUtils.loadClass("org.mozilla.javascript.tools.debugger.Main", getClass()); if (debuggerMain != null) { Method mainMethod = debuggerMain.getMethod( "mainEmbedded", ContextFactory.class, Scriptable.class, String.class); mainMethod.invoke(null, rhinoContextFactory, rhinoScope, "Debug embedded JavaScript."); rhinoDebuggerUp = true; } } catch (Exception e) { LOG.log(Level.WARNING, "Failed to launch Rhino debugger", e); } } rhinoContext = rhinoContextFactory.enterContext(); rhinoScope = rhinoContext.initStandardObjects(); try { ScriptableObject.defineClass(rhinoScope, JsAssert.class); ScriptableObject.defineClass(rhinoScope, Trace.class); ScriptableObject.defineClass(rhinoScope, Notifier.class); ScriptableObject.defineClass(rhinoScope, CountDownNotifier.class); // so that the stock test for IE can gracefully fail. rhinoContext.evaluateString(rhinoScope, "var window = new Object();", "<internal>", 0, null); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } finally { Context.exit(); } JsSimpleDomNode.register(rhinoScope); JsSimpleDomParser.register(rhinoScope); JsNamedNodeMap.register(rhinoScope); JsXMLHttpRequest.register(rhinoScope); }
/** Assemble the {@link JSLintResult} object. */ @NeedsContext private JSLintResult buildResults( final String systemId, final long startNanos, final long endNanos) { return (JSLintResult) contextFactory.call( new ContextAction() { public Object run(Context cx) { ResultBuilder b = new JSLintResult.ResultBuilder(systemId); b.duration(TimeUnit.NANOSECONDS.toMillis(endNanos - startNanos)); for (Issue issue : readErrors(systemId)) { b.addIssue(issue); } // Collect a report on what we've just linted. b.report(callReport(false)); // Extract JSLINT.data() output and set it on the result. Scriptable lintScope = (Scriptable) scope.get("JSLINT", scope); Object o = lintScope.get("data", lintScope); // Real JSLINT will always have this, but some of my test stubs don't. if (o != UniqueTag.NOT_FOUND) { Function reportFunc = (Function) o; Scriptable data = (Scriptable) reportFunc.call(cx, scope, scope, new Object[] {}); for (String global : Util.listValueOfType("globals", String.class, data)) { b.addGlobal(global); } for (String url : Util.listValueOfType("urls", String.class, data)) { b.addUrl(url); } for (Entry<String, Integer> member : getDataMembers(data).entrySet()) { b.addMember(member.getKey(), member.getValue()); } b.json(Util.booleanValue("json", data)); for (JSFunction f : Util.listValue("functions", data, new JSFunctionConverter())) { b.addFunction(f); } } return b.build(); } }); }
protected String compileUnits(JRCompilationUnit[] units, String classpath, File tempDirFile) throws JRException { Context context = ContextFactory.getGlobal().enterContext(); try { StringBuffer errors = new StringBuffer(); int errorCount = 0; for (int i = 0; i < units.length; i++) { JRCompilationUnit unit = units[i]; JavaScriptCompileData compileData = new JavaScriptCompileData(); for (Iterator it = unit.getExpressions().iterator(); it.hasNext(); ) { JRExpression expr = (JRExpression) it.next(); int id = unit.getCompileTask().getExpressionId(expr).intValue(); JavaScriptCompileData.Expression jsExpr = JavaScriptEvaluator.createJSExpression(expr); // compile the default expression to catch syntax errors try { context.compileString(jsExpr.getDefaultExpression(), "expression", 0, null); } catch (EvaluatorException e) { ++errorCount; appendError(errors, errorCount, e); } compileData.addExpression(id, jsExpr); } unit.setCompileData(compileData); } String errorsMessage = null; if (errorCount > 0) { errorsMessage = errorCount + " error(s):\n" + errors; } return errorsMessage; } finally { Context.exit(); } }
public void enterContext() { if (Context.getCurrentContext() != null) { Context.exit(); } ContextFactory.getGlobal().enterContext(mcJavascriptContext); }
static { ContextFactory.initGlobal(new DynamicScopeContextFactory()); }