Java Code Examples for org.mozilla.javascript.Context#setOptimizationLevel()

The following examples show how to use org.mozilla.javascript.Context#setOptimizationLevel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Bug482203Test.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testJavaApi() throws Exception {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1);
        Script script = cx.compileReader(new InputStreamReader(
                Bug482203Test.class.getResourceAsStream("Bug482203.js")),
                "", 1, null);
        Scriptable scope = cx.initStandardObjects();
        cx.executeScriptWithContinuations(script, scope);
        int counter = 0;
        for(;;)
        {
            Object cont = ScriptableObject.getProperty(scope, "c");
            if(cont == null)
            {
                break;
            }
            counter++;
            cx.resumeContinuation(cont, scope, null);
        }
        assertEquals(counter, 5);
        assertEquals(Double.valueOf(3), ScriptableObject.getProperty(scope, "result"));
    } finally {
    	Context.exit();
    }
}
 
Example 2
Source File: ComplianceTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private static Test createTest(final File testDir, final String name) {
    return new TestCase(name) {
        @Override
        public int countTestCases() {
            return 1;
        }
        @Override
        public void runBare() throws Throwable {
            final Context cx = Context.enter();
            try {
                cx.setOptimizationLevel(-1);
                final Scriptable scope = cx.initStandardObjects();
                ScriptableObject.putProperty(scope, "print", new Print(scope));
                createRequire(testDir, cx, scope).requireMain(cx, "program");
            }
            finally {
                Context.exit();
            }
        }
    };
}
 
Example 3
Source File: JSEngine.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 执行JS
 */
public String runScript(String functionParams, String methodName) {
    Context rhino = Context.enter();
    rhino.setOptimizationLevel(-1);
    try {
        Scriptable scope = rhino.initStandardObjects();

        ScriptableObject.putProperty(scope, "javaContext", Context.javaToJS(this, scope));
        ScriptableObject.putProperty(scope, "javaLoader", Context.javaToJS(JSEngine.class.getClassLoader(), scope));
        rhino.evaluateString(scope, sb.toString(), JSEngine.class.getName(), 1, null);
        Function function = (Function) scope.get(methodName, scope);
        Object result = function.call(rhino, scope, scope, new Object[]{functionParams});
        if (result instanceof String) {
            return (String) result;
        } else if (result instanceof NativeJavaObject) {
            return (String) ((NativeJavaObject) result).getDefaultValue(String.class);
        } else if (result instanceof NativeObject) {
            return (String) ((NativeObject) result).getDefaultValue(String.class);
        }
        return result.toString();//(String) function.call(rhino, scope, scope, functionParams);
    } finally {
        Context.exit();
    }
}
 
Example 4
Source File: Bug482203Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
public void testJavaApi() throws Exception {
    Context cx = RhinoAndroidHelper.prepareContext();
    try {
        cx.setOptimizationLevel(-1);
        Script script = cx.compileString(TestUtils.readAsset("Bug482203.js"),
                "", 1, null);
        Scriptable scope = cx.initStandardObjects();
        cx.executeScriptWithContinuations(script, scope);
        int counter = 0;
        for(;;)
        {
            Object cont = ScriptableObject.getProperty(scope, "c");
            if(cont == null)
            {
                break;
            }
            counter++;
            cx.resumeContinuation(cont, scope, null);
        }
        assertEquals(counter, 5);
        assertEquals(Double.valueOf(3), ScriptableObject.getProperty(scope, "result"));
    } finally {
    	Context.exit();
    }
}
 
Example 5
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
/**
 * Since a continuation can only capture JavaScript frames and not Java
 * frames, ensure that Rhino throws an exception when the JavaScript frames
 * don't reach all the way to the code called by
 * executeScriptWithContinuations or callFunctionWithContinuations.
 */
public void testErrorOnEvalCall() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString("eval('myObject.f(3);');",
                "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw IllegalStateException");
    } catch (WrappedException we) {
        Throwable t = we.getWrappedException();
        assertTrue(t instanceof IllegalStateException);
        assertTrue(t.getMessage().startsWith("Cannot capture continuation"));
    } finally {
        Context.exit();
    }
}
 
Example 6
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
public void testScriptWithNestedContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString("myObject.g( myObject.f(1) ) + 2;",
                "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        try {
            Object applicationState = pending.getApplicationState();
            assertEquals(new Integer(1), applicationState);
            int saved = (Integer) applicationState;
            cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1);
            fail("Should throw another ContinuationPending");
        } catch (ContinuationPending pending2) {
            Object applicationState2 = pending2.getApplicationState();
            assertEquals(new Integer(4), applicationState2);
            int saved2 = (Integer) applicationState2;
            Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 2);
            assertEquals(8, ((Number)result2).intValue());
        }
    } finally {
        Context.exit();
    }
}
 
Example 7
Source File: DoctestsTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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();
    }
}
 
Example 8
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testFunctionWithContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        cx.evaluateString(globalScope,
                "function f(a) { return myObject.f(a); }",
                "function test source", 1, null);
        Function f = (Function) globalScope.get("f", globalScope);
        Object[] args = { 7 };
        cx.callFunctionWithContinuations(f, globalScope, args);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        Object applicationState = pending.getApplicationState();
        assertEquals(7, ((Number)applicationState).intValue());
        int saved = (Integer) applicationState;
        Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1);
        assertEquals(8, ((Number)result).intValue());
    } finally {
        Context.exit();
    }
}
 
Example 9
Source File: ProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Object[] compileScript(Context cx, String scriptStr, Scriptable scriptScope, File f) {
    int opt = cx.getOptimizationLevel();
    cx.setOptimizationLevel(-1);
    Script script = cx.compileString(scriptStr, f.getName(), 1, null);
    script.exec(cx, scriptScope);
    Object[] ids = scriptScope.getIds();
    cx.setOptimizationLevel(opt);
    script = cx.compileString(scriptStr, f.getName(), 1, null);
    script.exec(cx, scriptScope);
    return ids;
}
 
Example 10
Source File: DecryptionUtils.java    From youtube-jextractor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates JS context with all objects and functions to execute decryption function in future
 *
 * @param jsObjects js objects that are referenced in a decryption function
 * @return JS context with all objects and functions to execute decryption function
 */
private Context prepareJsContext(List<String> jsObjects) {
    Context jsContext = Context.enter();
    jsContext.setOptimizationLevel(-1);
    scope = jsContext.initStandardObjects();
    for (String jsObject : jsObjects) {
        jsContext.evaluateString(scope, jsObject, "", 0, null);
    }
    return jsContext;
}
 
Example 11
Source File: Bug708801Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Override
protected Context makeContext() {
    Context cx = super.makeContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(COMPILER_MODE);
    return cx;
}
 
Example 12
Source File: Rhino.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void putScopeObject(String name, Object obj) {
    try {
        Context cx = Context.enter();
        cx.setOptimizationLevel(-1); // always interpretive mode          
        ScriptableObject.putProperty(scope, name, Context.javaToJS(obj, scope));
    } finally {
        Context.exit();            
    }            
}
 
Example 13
Source File: Rhino.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void putScopeMap(Map<String, Object> params) throws ScriptExecException {
    try {
        Context cx = Context.enter();
        cx.setOptimizationLevel(-1); // always interpretive mode     
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            ScriptableObject.putProperty(scope, entry.getKey(), Context.javaToJS(entry.getValue(), scope));
        }
    } finally {
        Context.exit();            
    }            
}
 
Example 14
Source File: SunSpiderBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{

    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "SunSpider-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example 15
Source File: V8Benchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{


    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "V8-Benchmark-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example 16
Source File: JsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
static boolean check( String source, int lineNumber )
{
	Context cx = Context.enter( );

	Debugger oldDebugger = cx.getDebugger( );
	Object oldContext = cx.getDebuggerContextData( );
	boolean oldGenerate = cx.isGeneratingDebug( );
	int oldLevel = cx.getOptimizationLevel( );

	try
	{
		BreakableSourceChecker checker = new BreakableSourceChecker( );
		checker.lineNumber = lineNumber + 2;

		cx.setDebugger( checker, null );
		cx.setGeneratingDebug( true );
		cx.setOptimizationLevel( -1 );

		cx.compileString( addHeader( source ), "<check>", 1, null ); //$NON-NLS-1$

		return checker.breakable;
	}
	catch ( Exception e )
	{
		return false;
	}
	finally
	{
		cx.setDebugger( oldDebugger, oldContext );
		cx.setGeneratingDebug( oldGenerate );
		cx.setOptimizationLevel( oldLevel );

		Context.exit( );
	}
}
 
Example 17
Source File: JsGlobal.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
private void init(Context cx) {
	cx.setOptimizationLevel(-1);
	// 添加bug
	cx.setDebugger(JsDebug.getInstance(), null);
	putConst("device", this, UiDevice.getInstance());
	putConst("event", this, new JsDroidEvent());
	putConst("include", this, new IncludeFucntion());
	putConst("loadapk", this, new LoadApkFunction());
	putConst("print", this, new PrintFunction());
	putConst("toast", this, new ToastFunction());
	putConst("input", this, new InputFunction());
	putConst("log", this, new LogFunction());
	putConst("findView", this, new FindViewFunction());
	putConst("findViews", this, new FindViewsFunction());
	putConst("findPic", this, new FindPicFunction());
	putConst("findImg", this, new FindImgFunction());
	putConst("time", this, new TimeFunction());
	putConst("sleep", this, new SleepFunction());
	putConst("saveScreen", this, new SaveScreenFunction());
	putConst("deleteScreen", this, new DeleteScreenFunction());
	putConst("clearImages", this, new ClearImageFunction());
	putConst("getXml", this, new XmlFunction());
	putConst("screenshot", this, new ScreenshotFunction());
	putConst("quit", this, new QuitFunction());
	putConst("config", this, Config.getInstance());
	// putConst("saveConfig", this, new SaveConfigFunction());
	// 加载mqm.js
	cx.evaluateString(this, "include('assets/mqm.js')", "<init>", 1, null);
}
 
Example 18
Source File: JavaScriptEngine.java    From commons-bsf with Apache License 2.0 4 votes vote down vote up
/**
     * Return an object from an extension.
     * @param object Object on which to make the call (ignored).
     * @param method The name of the method to call.
     * @param args an array of arguments to be
     * passed to the extension, which may be either
     * Vectors of Nodes, or Strings.
     */
    public Object call(Object object, String method, Object[] args)
        throws BSFException {

        Object retval = null;
        Context cx;

        try {
            cx = Context.enter();

            // REMIND: convert arg list Vectors here?

            Object fun = global.get(method, global);
            // NOTE: Source and line arguments are nonsense in a call().
            //       Any way to make these arguments *sensible?
            if (fun == Scriptable.NOT_FOUND)
                throw new EvaluatorException("function " + method +
                                             " not found.", "none", 0);

            cx.setOptimizationLevel(-1);
            cx.setGeneratingDebug(false);
            cx.setGeneratingSource(false);
            cx.setOptimizationLevel(0);
            cx.setDebugger(null, null);
            
            retval =
                ((Function) fun).call(cx, global, global, args);
            
//                ScriptRuntime.call(cx, fun, global, args, global);

            if (retval instanceof Wrapper)
                retval = ((Wrapper) retval).unwrap();
        } 
        catch (Throwable t) {
            handleError(t);
        } 
        finally {
            Context.exit();
        }
        return retval;
    }
 
Example 19
Source File: RequireJarTest.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
private Context createContext()
{
    final Context cx = Context.enter(); 
    cx.setOptimizationLevel(-1);
    return cx;
}
 
Example 20
Source File: ExpressionLanguageJavaScriptImpl.java    From oval with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Script load(final String expression) {
   final Context ctx = ContextFactory.getGlobal().enterContext();
   ctx.setOptimizationLevel(9);
   return ctx.compileString(expression, "<cmd>", 1, null);
}