Java Code Examples for org.mozilla.javascript.ContextFactory

The following are top voted examples for showing how to use org.mozilla.javascript.ContextFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: whackpad   File: JsTestsBase.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 2
Project: whackpad   File: ContextFactoryTest.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 3
Project: whackpad   File: DoctestsTest.java   View source code 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 4
Project: whackpad   File: CustomSetterAcceptNullScriptableTest.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 5
Project: whackpad   File: Bug496585.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 6
Project: phonk   File: AppRunnerInterpreter.java   View source code 6 votes vote down vote up
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);
}
 
Example 7
Project: jasperreports   File: JavaScriptEvaluatorScope.java   View source code 6 votes vote down vote up
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;
}
 
Example 8
Project: oval   File: ExpressionLanguageJavaScriptImpl.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 9
Project: code404   File: JsTestsBase.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 10
Project: code404   File: ContextFactoryTest.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 11
Project: code404   File: Bug496585Test.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 12
Project: code404   File: DoctestsTest.java   View source code 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 13
Project: code404   File: CustomSetterAcceptNullScriptableTest.java   View source code 6 votes vote down vote up
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();
		}
	}
 
Example 14
Project: scripturian   File: RhinoAdapter.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 15
Project: js-symbolic-executor   File: CompareFiles.java   View source code 6 votes vote down vote up
/**
 * @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;
}
 
Example 16
Project: js-symbolic-executor   File: SymbolicOperationAdapterTest.java   View source code 6 votes vote down vote up
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());
}
 
Example 17
Project: DataCleaner   File: JavaScriptAdvancedTransformer.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 18
Project: rhino-jscover   File: JsTestsBase.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 19
Project: rhino-jscover   File: ContextFactoryTest.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 20
Project: rhino-jscover   File: Bug496585Test.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 21
Project: rhino-jscover   File: DoctestsTest.java   View source code 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 22
Project: rhino-jscover   File: CustomSetterAcceptNullScriptableTest.java   View source code 6 votes vote down vote up
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();
		}
	}
 
Example 23
Project: astor   File: JsTestsBase.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 24
Project: astor   File: ContextFactoryTest.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 25
Project: astor   File: Bug496585Test.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 26
Project: astor   File: DoctestsTest.java   View source code 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 27
Project: astor   File: CustomSetterAcceptNullScriptableTest.java   View source code 6 votes vote down vote up
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();
		}
	}
 
Example 28
Project: AnalyzerBeans   File: JavaScriptAdvancedTransformer.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 29
Project: AnalyzerBeans   File: JavaScriptTransformer.java   View source code 6 votes vote down vote up
@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();
	}
}
 
Example 30
Project: Rhino-Prov-Mod   File: JsTestsBase.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 31
Project: Rhino-Prov-Mod   File: ContextFactoryTest.java   View source code 6 votes vote down vote up
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();
    }
}
 
Example 32
Project: Rhino-Prov-Mod   File: Bug496585Test.java   View source code 6 votes vote down vote up
@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;
        }
    });
}
 
Example 33
Project: Rhino-Prov-Mod   File: DoctestsTest.java   View source code 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 34
Project: Rhino-Prov-Mod   File: CustomSetterAcceptNullScriptableTest.java   View source code 6 votes vote down vote up
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();
		}
	}
 
Example 35
Project: BotLogic   File: GameManager.java   View source code 6 votes vote down vote up
@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();
}
 
Example 36
Project: StaticCMS   File: OGoPubJavaScriptAssociation.java   View source code 6 votes vote down vote up
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();
  }
}
 
Example 37
Project: birt   File: JavascriptEngineFactory.java   View source code 6 votes vote down vote up
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 );
		}

	}
}
 
Example 38
Project: alfresco-enhanced-script-environment   File: RemoteScriptDebugger.java   View source code 6 votes vote down vote up
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();
        }
    }
}
 
Example 39
Project: https-github.com-hyb1996-NoRootScriptDroid   File: RhinoAndroidHelper.java   View source code 5 votes vote down vote up
/**
 * @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;
}
 
Example 40
Project: https-github.com-hyb1996-NoRootScriptDroid   File: RhinoJavaScriptEngine.java   View source code 5 votes vote down vote up
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;
}