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

The following examples show how to use org.mozilla.javascript.Context#exit() . 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: DefineClassMapInheritance.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws IllegalAccessException, InstantiationException,
        InvocationTargetException {
    Context cx = Context.enter();
    try {
        ScriptableObject scope = cx.initStandardObjects();

        // define two classes that share a parent prototype
        ScriptableObject.defineClass(scope, Fruit.class, false, true);
        ScriptableObject.defineClass(scope, Vegetable.class, false, true);

        assertEquals(Boolean.TRUE,
                evaluate(cx, scope, "(new Fruit instanceof Food)"));
        assertEquals(Boolean.TRUE,
                evaluate(cx, scope, "(new Vegetable instanceof Food)"));
    } finally {
        Context.exit();
    }
}
 
Example 2
Source File: CipherManager.java    From YouTubeExtractor with Apache License 2.0 6 votes vote down vote up
private static String RhinoEngine(String s) {
	Context rhino = Context.enter();
	rhino.setOptimizationLevel(-1);
	try {
		Scriptable scope = rhino.initStandardObjects();
		rhino.evaluateString(scope, cachedDechiperFunction, "JavaScript", 1, null);
		Object obj = scope.get("decipher", scope);

		if (obj instanceof Function) {
			Function jsFunction = (Function) obj;
			Object jsResult = jsFunction.call(rhino, scope, scope, new Object[]{s});
			String result = Context.toString(jsResult);
			return result ;
		}
	}
	finally {
		Context.exit();
	}
	return s;
}
 
Example 3
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 4
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.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 5
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 6
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testScriptWithContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString("myObject.f(3) + 1;",
                "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {

        Object applicationState = pending.getApplicationState();
        assertEquals(new Integer(3), applicationState);
        int saved = (Integer) applicationState;
        Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1);
        assertEquals(5, ((Number)result).intValue());

    } finally {
        Context.exit();
    }
}
 
Example 7
Source File: SdpProcessor.java    From openwebrtc-android-sdk with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private SdpProcessor() {
    Context context = Context.enter();
    context.setOptimizationLevel(-1);
    context.setLanguageVersion(Context.VERSION_1_8);
    mScope = context.initStandardObjects();

    try {
        context.evaluateString(mScope, sSdpJsSource, "sdp.js", 1, null);
        mSdpToJsonFunction = context.compileFunction(mScope, "function sdpToJson(sdp) { return JSON.stringify(SDP.parse(sdp)); }", "sdpToJson", 1, null);
        mJsonToSdpFunction = context.compileFunction(mScope, "function jsonToSdp(sdp) { return SDP.generate(JSON.parse(sdp)); }", "jsonToSdp", 1, null);
    } finally {
        Context.exit();
    }
}
 
Example 8
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param expr
 * @param bindings
 * @param onlyFromDirectReferenceExpr
 * @return
 * @throws DataException
 */
public static Set<IDimLevel> getReferencedDimLevel( String expr )
		throws CoreException
{
	if ( expr == null  )
		return new HashSet<IDimLevel>( );
	try
	{
		Set<IDimLevel> result = new HashSet<IDimLevel>( );
		Context cx = Context.enter( );
		CompilerEnvirons ce = new CompilerEnvirons( );
		Parser p = new Parser( ce, cx.getErrorReporter( ) );
		AstRoot tree = p.parse( expr, null, 0 );
		IRFactory ir = new IRFactory( ce );
		ScriptNode script = ir.transformTree( tree );
		populateDimLevels( null, script, result );
		return result;
	}
	catch( Exception e )
	{
		return Collections.emptySet( );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 9
Source File: ColumnBindingTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @throws Exception
 */
private void genDummy1( ) throws Exception
{	
	expectedValue = new ArrayList( );
	
	Context context = Context.enter( );		
	Scriptable scope = context.initStandardObjects( );		
	Context.exit( );
	
	//------------generation----------------
	QueryDefinition qd = new QueryDefinition( );
	
	// prepare
	IBaseExpression[] rowBeArray = getDummyRowExpr( );
	prepareExprNameAndQuery( rowBeArray, null, qd );
	
	// generation
	IQueryResults qr = myGenDataEngine.prepare( qd ).execute( scope );
	
	// important step
	queryResultID = qr.getID( );
	
	IResultIterator ri = qr.getResultIterator( );		
	while ( ri.next( ) )
	{
		for ( int i = 0; i < rowBeArray.length; i++ )
			expectedValue.add( ri.getValue( this.rowExprName[i] ) );
	}
	
	ri.close( );
	qr.close( );
	myGenDataEngine.shutdown( );
}
 
Example 10
Source File: RhinoScriptProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Pre initializes two scope objects (one secure and one not) with the standard objects preinitialised.
 * This saves on very expensive calls to reinitialize a new scope on every web script execution. See
 * http://www.mozilla.org/rhino/scopes.html
 * 
 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
 */
public void afterPropertiesSet() throws Exception
{
    // Initialize the secure scope
    Context cx = Context.enter();
    try
    {
        cx.setWrapFactory(wrapFactory);
        this.secureScope = initScope(cx, false, true);
    }
    finally
    {
        Context.exit();
    }
    
    // Initialize the non-secure scope
    cx = Context.enter();
    try
    {
        cx.setWrapFactory(sandboxFactory);
        this.nonSecureScope = initScope(cx, true, true);
    }
    finally
    {
        Context.exit();
    }
}
 
Example 11
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public void testScriptWithMultipleContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString(
            "myObject.f(3) + myObject.g(3) + 2;",
            "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        try {
            Object applicationState = pending.getApplicationState();
            assertEquals(new Integer(3), 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(6), applicationState2);
            int saved2 = (Integer) applicationState2;
            Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 1);
            assertEquals(13, ((Number)result2).intValue());
        }
    } finally {
        Context.exit();
    }
}
 
Example 12
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The constructor.
 * 
 */
public AbstractScriptHandler( )
{
	final Context cx = Context.enter( );
	try
	{
		// scope = cx.initStandardObjects();
		scope = new ImporterTopLevel( cx );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 13
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the JavaScript funtion by given name.
 * 
 * @param sFunctionName
 *            The name of the function to be searched for
 * @return An instance of the function being searched for or null if it
 *         isn't found
 */
private final Function getJavascriptFunction( String sFunctionName )
{
	// TODO: CACHE PREVIOUSLY CREATED FUNCTION REFERENCES IN A HASHTABLE?

	// use names cache for quick validation to improve performance
	if ( javaScriptFunctionNamesCache == null
			|| javaScriptFunctionNamesCache.indexOf( sFunctionName ) < 0 )
	{
		return null;
	}

	Context.enter( );
	try
	{
		final Object oFunction = scope.get( sFunctionName, scope );
		if ( oFunction != Scriptable.NOT_FOUND
				&& oFunction instanceof Function )
		{
			return (Function) oFunction;
		}
		return null;
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 14
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 15
Source File: BirtCompTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@After
   public void tearDown()
{
	Context.exit( );
}
 
Example 16
Source File: Bug688023Test.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    Context.exit();
}
 
Example 17
Source File: Bug687669Test.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    Context.exit();
}
 
Example 18
Source File: ReportDesign.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
private void initFunctions( )
{
	Method[] tmpMethods = this.getClass( ).getDeclaredMethods( );
	HashMap<String, Method> methods = new LinkedHashMap<String, Method>( );
	for ( int i = 0; i < tmpMethods.length; i++ )
	{
		Method tmpMethod = tmpMethods[i];
		String methodName = tmpMethod.getName( );
		// must handle special case with long parameter or polymiorphism
		if ( "getReportElementByID".equals( methodName ) //$NON-NLS-1$
				|| "setUserProperty".equals( methodName ) ) //$NON-NLS-1$
			continue;
		if ( ( tmpMethod.getModifiers( ) & Modifier.PUBLIC ) != 0 )
			methods.put( methodName, tmpMethod );
	}

	Context.enter( );
	try
	{
		for ( final Entry<String, Method> entry : methods.entrySet( ) )
		{
			this.defineProperty( entry.getKey( ), new BaseFunction( ) {

				private static final long serialVersionUID = 1L;

				public Object call( Context cx, Scriptable scope,
						Scriptable thisObj, Object[] args )
				{
					Object[] convertedArgs = JavascriptEvalUtil
							.convertToJavaObjects( args );
					try
					{
						Method method = entry.getValue( );
						return method.invoke( ReportDesign.this,
								convertedArgs );
					}
					catch ( Exception e )
					{
						throw new WrappedException( e );
					}
				}

			}, DONTENUM );
		}
	}
	finally
	{
		Context.exit( );
	}

	this.defineProperty( "getReportElementByID", //$NON-NLS-1$
			new Function_getReportElementByID( ), DONTENUM );
	this.defineProperty( "setUserProperty", //$NON-NLS-1$
			new Function_setUserProperty( ), DONTENUM );
}
 
Example 19
Source File: NativeDateTimeSpanTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@After
   public void tearDown()
{
	Context.exit( );
}
 
Example 20
Source File: BirtStrTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
@After
   public void tearDown()
{
	Context.exit( );
}