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

The following examples show how to use org.mozilla.javascript.Context#initStandardObjects() . 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: ArrayConcatTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testArrayConcat() {
final String script = "var a = ['a0', 'a1'];\n"
	+ "a[3] = 'a3';\n"
	+ "var b = ['b1', 'b2'];\n"
	+ "b.concat(a)";

final ContextAction action = new ContextAction()
{
	public Object run(final Context _cx)
	{
		final ScriptableObject scope = _cx.initStandardObjects();
		final Object result = _cx.evaluateString(scope, script, "test script", 0, null);
		assertEquals("b1,b2,a0,a1,,a3", Context.toString(result));
		return null;
	}
};

Utils.runWithAllOptimizationLevels(action);
  }
 
Example 2
Source File: DeletePropertyTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
/**
 * delete should not delete anything in the prototype chain.
 */
@Test
public void testDeletePropInPrototype() throws Exception {
	final String script = "Array.prototype.foo = function() {};\n"
		+ "Array.prototype[1] = function() {};\n"
		+ "var t = [];\n"
		+ "[].foo();\n"
		+ "for (var i in t) delete t[i];\n"
		+ "[].foo();\n"
		+ "[][1]();\n";

	final ContextAction action = new ContextAction()
	{
		public Object run(final Context _cx)
		{
			final ScriptableObject scope = _cx.initStandardObjects();
			final Object result = _cx.evaluateString(scope, script, "test script", 0, null);
			return null;
		}
	};

	Utils.runWithAllOptimizationLevels(action);
}
 
Example 3
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 4
Source File: JsonExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testConvertApplicationLastResultSimpleSemanticInterpretation()
        throws Exception {
    final JsonExtensionNotificationDataConverter converter = new JsonExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = 'yes';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yeah", .75f, "voice", out);
    list.add(result);
    final String json = (String) converter
            .convertApplicationLastResult(list);
    Assert.assertEquals("vxml.input = {\"utterance\":\"yeah\","
            + "\"confidence\":0.75,\"interpretation\":\"yes\","
            + "\"mode\":\"voice\"}", json);
}
 
Example 5
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 6
Source File: RhinoWorkerUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static Scriptable parse(File source, String encoding, Action<Context> contextConfig) {
    Context context = Context.enter();
    if (contextConfig != null) {
        contextConfig.execute(context);
    }

    Scriptable scope = context.initStandardObjects();
    try {
        Reader reader = new InputStreamReader(new FileInputStream(source), encoding);
        try {
            context.evaluateReader(scope, reader, source.getName(), 0, null);
        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        Context.exit();
    }

    return scope;
}
 
Example 7
Source File: RequireJarTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@Override
public void testSetMainForAlreadyLoadedModule() throws Exception {
    final Context cx = createContext();
    final Scriptable scope = cx.initStandardObjects();
    final Require require = getSandboxedRequire(cx, scope, false);
    require.install(scope);
    cx.evaluateReader(scope, getReader("testSetMainForAlreadyLoadedModule.js"), 
            "testSetMainForAlreadyLoadedModule.js", 1, null);
    try {
        require.requireMain(cx, "assert");
        fail();
    }
    catch(IllegalStateException e) {
        assertEquals(e.getMessage(), "Attempt to set main module after it was loaded");
    }
}
 
Example 8
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 9
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 10
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 11
Source File: GeneratedMethodNameTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public void doTest(final String scriptCode) throws Exception {
	final Context cx = new RhinoAndroidHelper().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 12
Source File: PrimitiveTypeScopeResolutionTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
/**
 * Test that FunctionObject use the right top scope to loadClass a primitive
 * to an object
 */
@Test
public void functionObjectPrimitiveToObject() throws Exception {
    final String scriptScope2 = "function f() {\n"
        + "String.prototype.foo = 'from 2'; \n"
        + "var s2 = 's2';\n"
        + "var s2Foo = s2.foo;\n"
        + "var s2FooReadByFunction = myObject.readPropFoo(s2);\n"
        + "if (s2Foo != s2FooReadByFunction)\n"
        + "throw 's2 got: ' + s2FooReadByFunction;\n"
        + "}";

    // define object with custom method
    final MyObject myObject = new MyObject();
    final String[] functionNames = { "readPropFoo" };
    myObject.defineFunctionProperties(functionNames, MyObject.class,
        ScriptableObject.EMPTY);

    final String scriptScope1 = "String.prototype.foo = 'from 1'; scope2.f()";

    final ContextAction action = new ContextAction()
    {
        public Object run(final Context cx)
        {
            final Scriptable scope1 = cx.initStandardObjects(
                new MySimpleScriptableObject("scope1"));
            final Scriptable scope2 = cx.initStandardObjects(
                new MySimpleScriptableObject("scope2"));

            scope2.put("myObject", scope2, myObject);
            cx.evaluateString(scope2, scriptScope2, "source2", 1, null);

            scope1.put("scope2", scope1, scope2);

            return cx.evaluateString(scope1, scriptScope1, "source1", 1, null);
        }
    };
    Utils.runWithAllOptimizationLevels(action);
}
 
Example 13
Source File: RequireJarTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private Require getSandboxedRequire(Context cx, Scriptable scope, boolean sandboxed)
        throws URISyntaxException
{
    return new Require(cx, cx.initStandardObjects(),
            new StrongCachingModuleScriptProvider(
                    new UrlModuleSourceProvider(Collections.singleton(
                            getDirectory()), null)), null, null, true);
}
 
Example 14
Source File: RDTestCase.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
@Before
   public void rdSetUp() throws Exception
{

	
	index++;
	fileName = getOutputPath( ) + this.getClass().getSimpleName() + File.separator + this.getTestName() + File.separator  + "RptDocumentTemp" + File.separator + "testData_" + index;
	index++;
	fileName2 = getOutputPath( )+ this.getClass().getSimpleName() + File.separator + this.getTestName( ) + File.separator + "RptDocumentTemp" + File.separator + "testData_" + index;
	
	//make sure these 2 files are fresh
	deleteFile( new File( fileName ));
	deleteFile( new File( fileName2 ));
	
	DataEngineContext deContext1 = newContext( DataEngineContext.MODE_GENERATION,
			fileName,
			fileName2 );
	deContext1.setTmpdir( this.getTempDir( ) );
	myGenDataEngine = DataEngine.newDataEngine( deContext1 );

	myGenDataEngine.defineDataSource( this.dataSource );
	myGenDataEngine.defineDataSet( this.dataSet );

	Context context = Context.enter( );
	scope = context.initStandardObjects( );
	Context.exit( );
}
 
Example 15
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 16
Source File: NativeStringTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void assertEvaluates(final Object expected, final String source) {
    final ContextAction action = new ContextAction() {
        public Object run(Context cx) {
            final Scriptable scope = cx.initStandardObjects();
            final Object rep = cx.evaluateString(scope, source, "test.js",
                    0, null);
            assertEquals(expected, rep);
            return null;
        }
    };
    Utils.runWithAllOptimizationLevels(action);
}
 
Example 17
Source File: RequireTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public void testNonSandboxed() throws Exception {
    final Context cx = createContext();
    final Scriptable scope = cx.initStandardObjects();
    final Require require = getSandboxedRequire(cx, scope, false);
    final String jsFile = TestUtils.readAsset(dir + File.separator + "testNonSandboxed.js");
    ScriptableObject.putProperty(scope, "moduleUri", jsFile);
    require.requireMain(cx, "testNonSandboxed");
}
 
Example 18
Source File: RequireTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testNonSandboxed() throws Exception
{
    final Context cx = createContext();
    final Scriptable scope = cx.initStandardObjects();
    final Require require = getSandboxedRequire(cx, scope, false);
    final String jsFile = getClass().getResource("testNonSandboxed.js").toExternalForm();
    ScriptableObject.putProperty(scope, "moduleUri", jsFile);
    require.requireMain(cx, "testNonSandboxed");
}
 
Example 19
Source File: FunctionTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private void assertEvaluates(final Object expected, final String source) {
    final ContextAction action = new ContextAction() {
        public Object run(Context cx) {
            final Scriptable scope = cx.initStandardObjects();
            final Object rep = cx.evaluateString(scope, source, "test.js",
                    0, null);
            assertEquals(expected, rep);
            return null;
        }
    };
    Utils.runWithAllOptimizationLevels(action);
}
 
Example 20
Source File: RequireTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testRelativeId() throws Exception {
    final Context cx = createContext();
    final Scriptable scope = cx.initStandardObjects();
    final Require require = getSandboxedRequire(cx, scope, false);
    require.install(scope);
    cx.evaluateReader(scope, getReader("testRelativeId.js"),
            "testRelativeId.js", 1, null);
}