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

The following examples show how to use org.mozilla.javascript.Context#enter() . 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: Bug466207Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void setUp() {
    // set up a reference map
    reference = new ArrayList<Object>();
    reference.add("a");
    reference.add(Boolean.TRUE);
    reference.add(new HashMap<Object, Object>());
    reference.add(new Integer(42));
    reference.add("a");
    // get a js object as map
    Context context = Context.enter();
    ScriptableObject scope = context.initStandardObjects();
    list = (List<Object>) context.evaluateString(scope,
            "(['a', true, new java.util.HashMap(), 42, 'a']);",
            "testsrc", 1, null);
    Context.exit();
}
 
Example 2
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.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 3
Source File: DefineClassTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnnotatedHostObject() {
    Context cx = Context.enter();
    try {
        Object result = evaluate(cx, "a = new AnnotatedHostObject(); a.initialized;");
        assertEquals(result, Boolean.TRUE);
        assertEquals(evaluate(cx, "a.instanceFunction();"), "instanceFunction");
        assertEquals(evaluate(cx, "a.namedFunction();"), "namedFunction");
        assertEquals(evaluate(cx, "AnnotatedHostObject.staticFunction();"), "staticFunction");
        assertEquals(evaluate(cx, "AnnotatedHostObject.namedStaticFunction();"), "namedStaticFunction");
        assertNull(evaluate(cx, "a.foo;"));
        assertEquals(evaluate(cx, "a.foo = 'foo'; a.foo;"), "FOO");
        assertEquals(evaluate(cx, "a.bar;"), "bar");

        // Setting a property with no setting should be silently
        // ignored in non-strict mode.
        evaluate(cx, "a.bar = 'new bar'");
        assertEquals("bar", evaluate(cx, "a.bar;"));
    } finally {
        Context.exit();
    }
}
 
Example 4
Source File: NativeFinanceTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void setUp() throws Exception
{
	/*
	 * Creates and enters a Context. The Context stores information about
	 * the execution environment of a script.
	 */

	cx = Context.enter( );
	/*
	 * Initialize the standard objects (Object, Function, etc.) This must be
	 * done before scripts can be executed. Returns a scope object that we
	 * use in later calls.
	 */
	scope = cx.initStandardObjects( );

	new CoreJavaScriptInitializer().initialize( cx, scope );

}
 
Example 5
Source File: NativeJavaMapTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
@Before
   public void setUp() throws Exception
{
	/*
	 * Creates and enters a Context. The Context stores information about
	 * the execution environment of a script.
	 */

	cx = Context.enter( );
	/*
	 * Initialize the standard objects (Object, Function, etc.) This must be
	 * done before scripts can be executed. Returns a scope object that we
	 * use in later calls.
	 */
	scope = cx.initStandardObjects( );

	// ScriptableObject.defineClass(scope, NativeNamedList.class);

	registerBeans( );

}
 
Example 6
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 7
Source File: JsonExtensionNotificationDataConverter.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Packs the given SSML document into a JSON structure.
 * 
 * @param speakable
 *            the speakable with the SSML document
 * @return JSON formatted string
 */
private String toJson(final SpeakableText speakable) {
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_DEFAULT);
    final ScriptableObject scope = context.initStandardObjects();
    final String ssml = speakable.getSpeakableText();
    final Scriptable vxml = context.newObject(scope);
    ScriptableObject.putProperty(vxml, "ssml", ssml);
    return toJSON(vxml);
}
 
Example 8
Source File: OlapExpressionCompiler.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param expr
 * @param objectName
 * @return
 */
public static Set<String> getReferencedMeasure( String expr )
{
	if ( expr == null )
		return Collections.emptySet( );
	try
	{
		Set<String> result = new LinkedHashSet<String>( );
		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 );
		getScriptObjectName( script, "measure", result ); //$NON-NLS-1$
		
		return result;
	}
	catch( Exception e )
	{
		return Collections.emptySet( );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 9
Source File: JavaScriptEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * This is used by an application to evaluate a string containing
 * some expression.
 */
public Object eval(String source, int lineNo, int columnNo, Object oscript)
    throws BSFException {

    String scriptText = oscript.toString();
    Object retval = null;
    Context cx;

    try {
        cx = Context.enter();

        cx.setOptimizationLevel(-1);
        cx.setGeneratingDebug(false);
        cx.setGeneratingSource(false);
        cx.setOptimizationLevel(0);
        cx.setDebugger(null, null);

        retval = cx.evaluateString(global, scriptText,
                                   source, lineNo,
                                   null);

        if (retval instanceof NativeJavaObject)
            retval = ((NativeJavaObject) retval).unwrap();

    } 
    catch (Throwable t) { // includes JavaScriptException, rethrows Errors
        handleError(t);
    } 
    finally {
        Context.exit();
    }
    return retval;
}
 
Example 10
Source File: DataSessionContext.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets a top level scope for evaluating javascript expressions. This scope can be
 * either user provided, or one created by this adaptor
 */
public Scriptable getTopScope()
{
	if ( topScope == null )
	{
		// No scope provided by user; create one
		Context cx = Context.enter( );
		topScope = new DataAdapterTopLevelScope( cx, moduleHandle );
		Context.exit( );
	}
	return topScope;
}
 
Example 11
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public int g(int a) {
    Context cx = Context.enter();
    try {
        ContinuationPending pending = cx.captureContinuation();
        pending.setApplicationState(2*a);
        throw pending;
    } finally {
        Context.exit();
    }
}
 
Example 12
Source File: EmmaSemanticInterpretationExtractor.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs a new object.
 */
public EmmaSemanticInterpretationExtractor() {
    interpretations = new java.util.HashMap<String, Object>();
    interpretationTagNames = new java.util.Stack<String>();
    context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    scope = context.initStandardObjects();
}
 
Example 13
Source File: RhinoScriptProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ScriptProcessor#execute(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.util.Map)
 */
public Object execute(NodeRef nodeRef, QName contentProp, Map<String, Object> model)
{
    try
    {
        if (this.services.getNodeService().exists(nodeRef) == false)
        {
            throw new AlfrescoRuntimeException("Script Node does not exist: " + nodeRef);
        }
        
        if (contentProp == null)
        {
            contentProp = ContentModel.PROP_CONTENT;
        }
        ContentReader cr = this.services.getContentService().getReader(nodeRef, contentProp);
        if (cr == null || cr.exists() == false)
        {
            throw new AlfrescoRuntimeException("Script Node content not found: " + nodeRef);
        }
        
        // compile the script based on the node content
        Script script;
        Context cx = Context.enter();
        try
        {
            script = cx.compileString(resolveScriptImports(cr.getContentString()), nodeRef.toString(), 1, null);
        }
        finally
        {
            Context.exit();
        }
        
        return executeScriptImpl(script, model, false, nodeRef.toString());
    }
    catch (Throwable err)
    {
        throw new ScriptException("Failed to execute script '" + nodeRef.toString() + "': " + err.getMessage(), err);
    }
}
 
Example 14
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 15
Source File: CompilerTest.java    From JQF with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Before
public void initContext() {
    context = Context.enter();
}
 
Example 16
Source File: Bug689308Test.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    cx = Context.enter();
    cx.setLanguageVersion(Context.VERSION_1_8);
}
 
Example 17
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    cx = Context.enter();
    scope = cx.initStandardObjects();
    cx.setLanguageVersion(170);
}
 
Example 18
Source File: Bug685403Test.java    From rhino-android with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    cx = Context.enter();
    cx.setOptimizationLevel(-1);
    scope = cx.initStandardObjects();
}
 
Example 19
Source File: JsGlobal.java    From JsDroidCmd with Mozilla Public License 2.0 4 votes vote down vote up
private JsGlobal() {
	this(Context.enter());
}
 
Example 20
Source File: SubQueryTest.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Sub query test
 * Normal case: add subquery to GroupDefinition
 * @throws Exception
 */
@Test
   public void test( ) throws Exception
{
	// 1 prepare query execution
	Context cx = Context.enter( );
	Scriptable sharedScope = cx.initStandardObjects( );

	Scriptable subScope = cx.newObject( sharedScope );
	subScope.setParentScope( sharedScope );
	
	IQueryDefinition queryDefn = getDefaultQueryDefnWithSubQuery( dataSet.getName( ) );
	expressions = getExpressionsOfDefaultQuery( );
	
	// 2 do query execution
	IResultIterator resultIt = executeQuery( queryDefn );
	
	// 3.1 get sub query data
	resultIt.next( );
	IResultIterator subIterator = resultIt.getSecondaryIterator( "IAMTEST",
			sharedScope );
	
	// 3.2 get sub query of sub query data
	subIterator.next( );
	IResultIterator subSubIterator = subIterator.getSecondaryIterator( "IAMTEST2",
			subScope );

	bindingNameRow = this.getBindingExpressionName( );
	// 4.1 output sub query data
	testPrintln( "sub query data" );
	outputData( subIterator );
	testPrintln( "" );
	
	// 4.2 output sub query of sub query data
	testPrintln( "sub query of sub query data" );
	outputData( subSubIterator );
	testPrintln( "" );
	
	// check whether output is correct
	checkOutputFile();
}