public void runJsTests(File[] tests) throws IOException { ContextFactory factory = ContextFactory.getGlobal(); Context cx = factory.enterContext(); try { cx.setOptimizationLevel(this.optimizationLevel); Scriptable shared = cx.initStandardObjects(); for (File f : tests) { int length = (int) f.length(); // don't worry about very long // files char[] buf = new char[length]; new FileReader(f).read(buf, 0, length); String session = new String(buf); runJsTest(cx, shared, f.getName(), session); } } finally { Context.exit(); } }
public void testCustomContextFactory() { ContextFactory factory = new MyFactory(); Context cx = factory.enterContext(); try { Scriptable globalScope = cx.initStandardObjects(); // Test that FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME is enabled /* TODO(stevey): fix this functionality in parser Object result = cx.evaluateString(globalScope, "var obj = {};" + "function obj.foo() { return 'bar'; }" + "obj.foo();", "test source", 1, null); assertEquals("bar", result); */ } catch (RhinoException e) { fail(e.toString()); } finally { Context.exit(); } }
@Test public void runDoctest() throws Exception { ContextFactory factory = ContextFactory.getGlobal(); Context cx = factory.enterContext(); try { cx.setOptimizationLevel(optimizationLevel); Global global = new Global(cx); // global.runDoctest throws an exception on any failure int testsPassed = global.runDoctest(cx, global, source, name, 1); System.out.println(name + "(" + optimizationLevel + "): " + testsPassed + " passed."); assertTrue(testsPassed > 0); } catch (Exception ex) { System.out.println(name + "(" + optimizationLevel + "): FAILED due to "+ex); throw ex; } finally { Context.exit(); } }
public void testSetNullForScriptableSetter() throws Exception { final String scriptCode = "foo.myProp = new Foo2();\n" + "foo.myProp = null;"; final ContextFactory factory = new ContextFactory(); final Context cx = factory.enterContext(); try { final ScriptableObject topScope = cx.initStandardObjects(); final Foo foo = new Foo(); // define custom setter method final Method setMyPropMethod = Foo.class.getMethod("setMyProp", Foo2.class); foo.defineProperty("myProp", null, null, setMyPropMethod, ScriptableObject.EMPTY); topScope.put("foo", topScope, foo); ScriptableObject.defineClass(topScope, Foo2.class); cx.evaluateString(topScope, scriptCode, "myScript", 1, null); } finally { Context.exit(); } }
@Test public void callOverloadedFunction() { new ContextFactory().call(new ContextAction() { public Object run(Context cx) { cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585().method('one', 'two', 'three')", "<test>", 1, null); cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585().method('one', function() {})", "<test>", 1, null); return null; } }); }
public void init() { //this can be initiated only once if (mScriptContextFactory == null) { mScriptContextFactory = new ScriptContextFactory(); ContextFactory.initGlobal(mScriptContextFactory); } mScriptContextFactory.setInterpreter(this); rhino = Context.enter(); // observingDebugger = new ObservingDebugger(); // rhino.setDebugger(observingDebugger, new Integer(0)); // rhino.setGeneratingDebug(true); // give some android love rhino.setOptimizationLevel(-1); scope = rhino.initStandardObjects(); //let rhino do some java <-> js transformations for us rhino.getWrapFactory().setJavaPrimitiveWrap(false); }
protected static Context enter(Context context) { Context currentContext = Context.getCurrentContext(); if (context != null && context == currentContext) { // already the current context return currentContext; } // exit the current context if any if (currentContext != null) { Context.exit(); } Context newContext = ContextFactory.getGlobal().enterContext(context); if (log.isDebugEnabled()) { log.debug("entered context " + newContext + ", requested " + context); } return newContext; }
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException { LOG.debug("Evaluating JavaScript expression: {1}", expression); try { final Context ctx = ContextFactory.getGlobal().enterContext(); Script script = scriptCache.get(expression); if (script == null) { ctx.setOptimizationLevel(9); script = ctx.compileString(expression, "<cmd>", 1, null); scriptCache.put(expression, script); } final Scriptable scope = ctx.newObject(parentScope); scope.setPrototype(parentScope); scope.setParentScope(null); for (final Entry<String, ?> entry : values.entrySet()) { scope.put(entry.getKey(), scope, Context.javaToJS(entry.getValue(), scope)); } return script.exec(ctx, scope); } catch (final EvaluatorException ex) { throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex); } finally { Context.exit(); } }
@Test public void callOverloadedFunction() { new ContextFactory().call(new ContextAction() { public Object run(Context cx) { cx.getWrapFactory().setJavaPrimitiveWrap(false); Assert.assertEquals("string[]", cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585Test().method('one', 'two', 'three')", "<test>", 1, null)); Assert.assertEquals("string+function", cx.evaluateString( cx.initStandardObjects(), "new org.mozilla.javascript.tests.Bug496585Test().method('one', function() {})", "<test>", 1, null)); return null; } }); }
/** * Rhino implementation version. * * @return Rhino implementation version */ private static String getImplementationVersion() { Context context = new ContextFactory().enterContext(); try { String version = context.getImplementationVersion(); if( ( version != null ) && version.startsWith( "Rhino " ) ) version = version.substring( 6 ); return version; } finally { Context.exit(); } }
/** * @param maxTests the maximum number of tests to generate * @return the set of differences between the old and new programs, given as * pairs (x, y), where x is the {@link Output} from the original * program and y is the new program's output on {@code x.input} * @throws IOException */ public Set<Pair<Output, Object>> compare(FileLoader loader, int maxTests) throws IOException { Cvc3Context cvc3Context = Cvc3Context.create(arguments.length, loader); NewInputGenerator inputGenerator = new ApiBasedInputGenerator(cvc3Context); SymbolicExecutor executor = SymbolicExecutor.create( originalProgram, loader, inputGenerator, maxTests, entryFunction, arguments); Context rhinoContext = Context.enter(); Set<Pair<Output, Object>> differences = Sets.newHashSet(); // Run symbolic execution, and iterate through all generated inputs for (Output output : executor.run()) { // Run the new program with the old arguments ScriptableObject scope = rhinoContext.initStandardObjects(); rhinoContext.evaluateString(scope, loader.toString(newProgram), "new program", 0, null); Object result = ScriptableObject.callMethod(scope, entryFunction, output.input.toArray(ContextFactory.getGlobal())); // If the results differ, add them to the set of differences if (!output.result.equals(result)) { differences.add(new Pair<Output, Object>(output, result)); } } return differences; }
public void testfromJS() { Object symbolicOp = ContextFactory.getGlobal().call(new ContextEval( "({ getSymbol: function() {" + " return 'f';" + "}," + "getArg: function(n) {" + " return n===0 ? -11 : n===1 ? (1,2) : 44;" + "}," + "arity: function() {" + "return [0,0,0,0].length;" // This makes Rhino return a Double(4.), // which is what SymbolicOperationAdapter really sees. + "}" + "})")); assertEquals("(f -11.0 2.0 44.0 44.0)", SymbolicOperationAdapter.ADAPTER.fromJS(symbolicOp, AdapterList.DEFAULT_ADAPTERS).toString()); }
@Initialize public void init() { _contextFactory = new ContextFactory(); final Context context = _contextFactory.enterContext(); try { _script = context.compileString(sourceCode, this.getClass().getSimpleName(), 1, null); _sharedScope = context.initStandardObjects(); JavaScriptUtils.addToScope(_sharedScope, new JavaScriptLogger(), "logger", "log"); JavaScriptUtils.addToScope(_sharedScope, System.out, "out"); _script.exec(context, _sharedScope); _transformerObj = (NativeObject) _sharedScope.get("transformerObj"); if (_transformerObj == null) { throw new IllegalStateException("Required JS object 'transformerObj' not found!"); } _initializeFunction = (Function) _transformerObj.get("initialize"); _transformFunction = (Function) _transformerObj.get("transform"); _closeFunction = (Function) _transformerObj.get("close"); _initializeFunction.call(context, _sharedScope, _sharedScope, new Object[0]); } finally { Context.exit(); } }
@Initialize public void init() { _contextFactory = new ContextFactory(); Context context = _contextFactory.enterContext(); try { _script = context.compileString(sourceCode, this.getClass().getSimpleName(), 1, null); _sharedScope = context.initStandardObjects(); JavaScriptUtils.addToScope(_sharedScope, logger, "logger", "log"); JavaScriptUtils.addToScope(_sharedScope, System.out, "out"); _script.exec(context, _sharedScope); _transformerObj = (NativeObject) _sharedScope.get("transformerObj"); if (_transformerObj == null) { throw new IllegalStateException("Required JS object 'transformerObj' not found!"); } _initializeFunction = (Function) _transformerObj.get("initialize"); _transformFunction = (Function) _transformerObj.get("transform"); _closeFunction = (Function) _transformerObj.get("close"); _initializeFunction.call(context, _sharedScope, _sharedScope, new Object[0]); } finally { Context.exit(); } }
@Initialize public void init() { _contextFactory = new ContextFactory(); Context context = _contextFactory.enterContext(); try { _script = context.compileString(sourceCode, this.getClass() .getSimpleName(), 1, null); _sharedScope = context.initStandardObjects(); JavaScriptUtils.addToScope(_sharedScope, logger, "logger", "log"); JavaScriptUtils.addToScope(_sharedScope, System.out, "out"); } finally { Context.exit(); } }
@Override public void create() { Gdx.app.log(TAG, "created"); Tween.registerAccessor(ModelEntity.class, new ModelEntityAccessor()); Tween.registerAccessor(RTSCameraController.class, new CameraAccessor()); Tween.registerAccessor(RobotEntity.class, new RobotEntityAccessor()); ContextFactory.initGlobal(new ScriptContextFactory()); BotLogic.game = this; BotLogic.inputManager = new InputManager(); BotLogic.audio = new AudioManager(); BotLogic.skin = new FlatSkin(); BotLogic.models = new ModelManager(); BotLogic.sprites = new SpritesManager(); BotLogic.entities = new EntityManager(); BotLogic.config = new ConfigManager(); BotLogic.screens = new ScreenManager(this);// always last!!! BotLogic.config.load(); loading = false; fpsLogger = new FPSLogger(); BotLogic.screens.goToMainMenu(); }
public void compile() { if (this.scriptString == null) { log.error("association has no script?"); return; } try { Context ctx = ContextFactory.getGlobal().enterContext(); this.script = ctx.compileString (this.scriptString, "<association>", 1 /* line */, null /* security context */); } finally { Context.exit(); } }
public static void destroyMyFactory( ) { ContextFactory factory = ContextFactory.getGlobal( ); if ( factory != null && factory instanceof MyFactory ) { try { Class factoryClass = Class .forName( "org.mozilla.javascript.ContextFactory" ); Field field = factoryClass.getDeclaredField( "hasCustomGlobal" ); field.setAccessible( true ); field.setBoolean( factoryClass, false ); field = factoryClass.getDeclaredField( "global" ); field.setAccessible( true ); field.set( factoryClass, new ContextFactory( ) ); } catch ( Exception ex ) { logger.log( Level.WARNING, ex.getMessage( ), ex ); } } }
public synchronized void shutdown() { if (this.isActive()) { try { this.remoteDebugger.stop(); } catch (final Exception ex) { LOGGER.error("Error stopping remote debugger agent", ex); throw new WebScriptException("Error stopping remote debugger agent", ex); } ContextFactory.getGlobal().removeListener(this.remoteDebugger); this.remoteDebugger = null; for (final EnhancedScriptProcessor<?> scriptProcessor : this.scriptProcessors) { scriptProcessor.debuggerDetached(); } } }
/** * @return The Context factory which has to be used on android. */ @VisibleForTesting public AndroidContextFactory getContextFactory() { AndroidContextFactory factory; if (!ContextFactory.hasExplicitGlobal()) { factory = new AndroidContextFactory(cacheDirectory); ContextFactory.getGlobalSetter().setContextFactoryGlobal(factory); } else if (!(ContextFactory.getGlobal() instanceof AndroidContextFactory)) { throw new IllegalStateException("Cannot initialize factory for Android Rhino: There is already another factory"); } else { factory = (AndroidContextFactory) ContextFactory.getGlobal(); } return factory; }
protected Context createContext() { if (!ContextFactory.hasExplicitGlobal()) { ContextFactory.initGlobal(new InterruptibleAndroidContextFactory(new File(mAndroidContext.getCacheDir(), "classes"))); } Context context = new RhinoAndroidHelper(mAndroidContext).enterContext(); contextCount++; context.setOptimizationLevel(-1); context.setLanguageVersion(Context.VERSION_ES6); return context; }