org.mozilla.javascript.ContextFactory Java Examples

The following examples show how to use org.mozilla.javascript.ContextFactory. 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: RhinoExpression.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Evaluates the defined expression. If an exception or an evaluation error occures, the evaluation returns null and
 * the error is logged. The current datarow and a copy of the expressions properties are set to script-internal
 * variables. Changes to the properties will not alter the expressions original properties and will be lost when the
 * evaluation is finished.
 * <p/>
 * Expressions do not maintain a state and no assumptions about the order of evaluation can be made.
 *
 * @return the evaluated value or null.
 */
public Object getValue() {
  if ( expression == null ) {
    return null;
  }

  LegacyDataRowWrapper wrapper = null;
  try {
    final ContextFactory contextFactory = new ContextFactory();
    final Context context = contextFactory.enterContext();
    final Scriptable scope = context.initStandardObjects();
    wrapper = initializeScope( scope );

    final Object o = context.evaluateString( scope, expression, getName(), 1, null );
    if ( o instanceof NativeJavaObject ) {
      final NativeJavaObject object = (NativeJavaObject) o;
      return object.unwrap();
    }
    return o;
  } finally {
    if ( wrapper != null ) {
      wrapper.setParent( null );
    }
    Context.exit();
  }
}
 
Example #2
Source File: JsSimpleDomParser.java    From cxf with Apache License 2.0 6 votes vote down vote up
public Object jsFunction_parseFromString(String xml, String mimeType) {
    StringReader reader = new StringReader(xml);
    InputSource inputSource = new InputSource(reader);
    Document document;
    try {
        document = documentBuilder.parse(inputSource);
    } catch (SAXException | IOException e) {
        throw new RuntimeException(e);
    }

    Context context = ContextFactory.getGlobal().enterContext();
    try {
        JsSimpleDomNode domNode = (JsSimpleDomNode)context.newObject(getParentScope(), "Node");
        domNode.initialize(document, null);
        return domNode;
    } finally {
        Context.exit();
    }
}
 
Example #3
Source File: ExpressionLanguageJavaScriptImpl.java    From oval with Eclipse Public License 2.0 6 votes vote down vote up
@Override
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();
      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));
      }
      final Script expr = expressionCache.get(expression);
      return expr.exec(ctx, scope);
   } catch (final EvaluatorException ex) {
      throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex);
   } finally {
      Context.exit();
   }
}
 
Example #4
Source File: AppRunnerInterpreter.java    From PHONK with GNU General Public License v3.0 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 #5
Source File: JavascriptEngineFactory.java    From birt with Eclipse Public License 1.0 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 #6
Source File: JsTestsBase.java    From astor with GNU General Public License v2.0 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 #7
Source File: CustomSetterAcceptNullScriptableTest.java    From astor with GNU General Public License v2.0 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 #8
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 #9
Source File: ContextFactoryTest.java    From astor with GNU General Public License v2.0 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 #10
Source File: Bug496585Test.java    From astor with GNU General Public License v2.0 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 #11
Source File: ExpressionLanguageJavaScriptImpl.java    From oval with Eclipse Public License 2.0 5 votes vote down vote up
public ExpressionLanguageJavaScriptImpl() {
   final Context ctx = ContextFactory.getGlobal().enterContext();
   try {
      parentScope = ctx.initStandardObjects();
   } finally {
      Context.exit();
   }
}
 
Example #12
Source File: MappingJackson2XmlViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	request = new MockHttpServletRequest();
	response = new MockHttpServletResponse();

	jsContext = ContextFactory.getGlobal().enterContext();
	jsScope = jsContext.initStandardObjects();

	view = new MappingJackson2XmlView();
}
 
Example #13
Source File: RhinoExecutor.java    From caja with Apache License 2.0 5 votes vote down vote up
public <T> T run(Map<String, ?> actuals, Class<T> expectedResultType)
    throws AbnormalExitException {
  if (SANDBOXINGFACTORY != ContextFactory.getGlobal()) {
    throw new IllegalStateException();
  }
  Context context = SANDBOXINGFACTORY.enterContext();
  // Don't bother to compile tests to a class file.  Removing this causes
  // a 5x slow-down in Rhino-heavy tests.
  context.setOptimizationLevel(-1);
  try {
    return runInContext(context, actuals, expectedResultType);
  } finally {
    Context.exit();
  }
}
 
Example #14
Source File: Bug467396Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testOverloadedVarargs() {
    Context cx = ContextFactory.getGlobal().enterContext();
    try {
        Scriptable scope = cx.initStandardObjects();
        Object result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, 1)",
                "source", 1, null));
        assertTrue(result instanceof Object[]);
        assertEquals(1, ((Object[]) result).length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, [1])",
                "source", 1, null));
        assertTrue(result instanceof Object[]);
        assertEquals(1, ((Object[]) result).length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, [1, 1])",
                "source", 1, null));
        assertTrue(result instanceof Object[][]);
        assertEquals(1, ((Object[][]) result).length);
        assertEquals(1, ((Object[][]) result)[0].length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, 1, 1)",
                "source", 1, null));
        assertTrue(result instanceof Object[][]);
        assertEquals(1, ((Object[][]) result).length);
        assertEquals(1, ((Object[][]) result)[0].length);
    } finally {
        Context.exit();
    }
}
 
Example #15
Source File: GeneratedMethodNameTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void doTest(final String scriptCode) throws Exception {
	final Context cx = ContextFactory.getGlobal().enterContext();
	try {
           Scriptable topScope = cx.initStandardObjects();
   		topScope.put("javaNameGetter", topScope, new JavaNameGetter());
   		Script script = cx.compileString(scriptCode, "myScript", 1, null);
   		script.exec(cx, topScope);
	} finally {
	    Context.exit();
	}
}
 
Example #16
Source File: TypeOfTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void doTest(final int optimizationLevel, final String expected, final ContextAction action)
{
	Object o = new ContextFactory().call(new ContextAction()
		{
			public Object run(final Context context)
			{
				context.setOptimizationLevel(optimizationLevel);
				return Context.toString(action.run(context));
			}
		});
	assertEquals(expected, o);
}
 
Example #17
Source File: GeneratedClassNameTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void doTest(final String expectedName, final String scriptName)
    throws Exception
{
    final Script script = (Script) ContextFactory.getGlobal().call(
      new ContextAction() {
        public Object run(final Context context) {
          return context.compileString("var f = 1", scriptName, 1, null);
        }
      });

    // remove serial number
    String name = script.getClass().getSimpleName();
    assertEquals(expectedName, name.substring(0, name.lastIndexOf('_')));
}
 
Example #18
Source File: Utils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Runs the action successively with all available optimization levels
 */
public static void runWithAllOptimizationLevels(final ContextFactory contextFactory, final ContextAction action)
{
	runWithOptimizationLevel(contextFactory, action, -1);
	runWithOptimizationLevel(contextFactory, action, 0);
	runWithOptimizationLevel(contextFactory, action, 1);
}
 
Example #19
Source File: Utils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Runs the provided action at the given optimization level
 */
public static void runWithOptimizationLevel(final ContextFactory contextFactory, final ContextAction action, final int optimizationLevel)
{
   	final Context cx = contextFactory.enterContext();
   	try
   	{
   		cx.setOptimizationLevel(optimizationLevel);
   		action.run(cx);
   	}
   	finally
   	{
   		Context.exit();
   	}
}
 
Example #20
Source File: JavascriptEngineFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public static void initMyFactory( )
{
	ContextFactory.initGlobal( new MyFactory( ) );
	if ( System.getSecurityManager( ) != null )
	{
		SecurityController.initGlobal( ScriptUtil
				.createSecurityController( ) );
	}
}
 
Example #21
Source File: JsSimpleDomNode.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JsSimpleDomNode wrapNode(Scriptable scope, Node node) {
    if (node == null) {
        return null;
    }

    Context cx = ContextFactory.getGlobal().enterContext();
    try {
        JsSimpleDomNode newObject = (JsSimpleDomNode)cx.newObject(scope, "Node");
        newObject.initialize(node, null);
        return newObject;
    } finally {
        Context.exit();
    }
}
 
Example #22
Source File: BaseScript.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void initializeObjects() {
  final Context context = ContextFactory.getGlobal().enterContext();
  try {
    final Object wrappedFactory = Context.javaToJS( new DatasourceFactory(), scope );
    ScriptableObject.putProperty( scope, "datasourceFactory", wrappedFactory );
  } finally {
    context.exit();
  }
}
 
Example #23
Source File: GeneratedClassNameTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void doTest(final String expectedName, final String scriptName)
    throws Exception
{
    final Script script = (Script) ContextFactory.getGlobal().call(
      new ContextAction() {
        public Object run(final Context context) {
          return context.compileString("var f = 1", scriptName, 1, null);
        }
      });

    // remove serial number
    String name = script.getClass().getSimpleName();
    assertEquals(expectedName, name.substring(0, name.lastIndexOf('_')));
}
 
Example #24
Source File: MappingJackson2JsonViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	request = new MockHttpServletRequest();
	response = new MockHttpServletResponse();

	jsContext = ContextFactory.getGlobal().enterContext();
	jsScope = jsContext.initStandardObjects();

	view = new MappingJackson2JsonView();
}
 
Example #25
Source File: MappingJackson2JsonViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	request = new MockHttpServletRequest();
	response = new MockHttpServletResponse();

	jsContext = ContextFactory.getGlobal().enterContext();
	jsScope = jsContext.initStandardObjects();

	view = new MappingJackson2JsonView();
}
 
Example #26
Source File: MappingJackson2XmlViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() {
	request = new MockHttpServletRequest();
	response = new MockHttpServletResponse();

	jsContext = ContextFactory.getGlobal().enterContext();
	jsScope = jsContext.initStandardObjects();

	view = new MappingJackson2XmlView();
}
 
Example #27
Source File: SecureJavascriptConfigurator.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected synchronized void initSecureScriptContextFactory() {
  if (secureScriptContextFactory == null) {
    secureScriptContextFactory = new SecureScriptContextFactory();

    secureScriptContextFactory.setOptimizationLevel(getScriptOptimizationLevel());

    if (isEnableClassWhiteListing() || getWhiteListedClasses() != null
        || classWhitelister != null) {
      if (classWhitelister == null) {
        classWhitelister = new DefaultClassWhitelister();
        if (getWhiteListedClasses() != null && getWhiteListedClasses().size() > 0) {
          ((DefaultClassWhitelister)classWhitelister).setWhiteListedClasses(getWhiteListedClasses());
        }
      }
      secureScriptClassShutter = new SecureScriptClassShutter();
      secureScriptClassShutter.setClassWhitelister(classWhitelister);
      secureScriptContextFactory.setClassShutter(secureScriptClassShutter);
    }

    if (getMaxScriptExecutionTime() > 0L) {
      secureScriptContextFactory.setMaxScriptExecutionTime(getMaxScriptExecutionTime());
    }

    if (getMaxMemoryUsed() > 0L) {
      secureScriptContextFactory.setMaxMemoryUsed(getMaxMemoryUsed());
    }

    if (getMaxStackDepth() > 0) {
      secureScriptContextFactory.setMaxStackDepth(getMaxStackDepth());
    }

    if (getMaxScriptExecutionTime() > 0L || getMaxMemoryUsed() > 0L) {
      secureScriptContextFactory.setObserveInstructionCount(getNrOfInstructionsBeforeStateCheckCallback());
    }

    ContextFactory.initGlobal(secureScriptContextFactory);
  }
}
 
Example #28
Source File: RhinoAndroidHelper.java    From rhino-android with Apache License 2.0 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 #29
Source File: Bug467396Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public void testOverloadedVarargs() {
    Context cx = ContextFactory.getGlobal().enterContext();
    try {
        Scriptable scope = cx.initStandardObjects();
        Object result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, 1)",
                "source", 1, null));
        assertTrue(result instanceof Object[]);
        assertEquals(1, ((Object[]) result).length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, [1])",
                "source", 1, null));
        assertTrue(result instanceof Object[]);
        assertEquals(1, ((Object[]) result).length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, [1, 1])",
                "source", 1, null));
        assertTrue(result instanceof Object[][]);
        assertEquals(1, ((Object[][]) result).length);
        assertEquals(1, ((Object[][]) result)[0].length);
        result = unwrap(cx.evaluateString(scope,
                "java.lang.reflect.Array.newInstance(java.lang.Object, 1, 1)",
                "source", 1, null));
        assertTrue(result instanceof Object[][]);
        assertEquals(1, ((Object[][]) result).length);
        assertEquals(1, ((Object[][]) result)[0].length);
    } finally {
        Context.exit();
    }
}
 
Example #30
Source File: Utils.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the action successively with all available optimization levels
 */
public static void runWithAllOptimizationLevels(final ContextFactory contextFactory, final ContextAction action)
{
	runWithOptimizationLevel(contextFactory, action, -1);
	runWithOptimizationLevel(contextFactory, action, 0);
	runWithOptimizationLevel(contextFactory, action, 1);
}