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

The following examples show how to use org.mozilla.javascript.Context#compileString() . 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: 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 2
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testScriptWithNestedContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString("myObject.g( myObject.f(1) ) + 2;",
                "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        try {
            Object applicationState = pending.getApplicationState();
            assertEquals(new Integer(1), 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(4), applicationState2);
            int saved2 = (Integer) applicationState2;
            Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 2);
            assertEquals(8, ((Number)result2).intValue());
        }
    } finally {
        Context.exit();
    }
}
 
Example 3
Source File: Main.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
static void evalInlineScript(Context cx, String scriptText) {
    try {
        Script script = cx.compileString(scriptText, "<command>", 1, null);
        if (script != null) {
            script.exec(cx, getShellScope());
        }
    } catch (RhinoException rex) {
        ToolErrorReporter.reportException(
                cx.getErrorReporter(), rex);
        exitCode = EXITCODE_RUNTIME_ERROR;
    } catch (VirtualMachineError ex) {
        // Treat StackOverflow and OutOfMemory as runtime errors
        ex.printStackTrace();
        String msg = ToolErrorReporter.getMessage(
                "msg.uncaughtJSException", ex.toString());
        Context.reportError(msg);
        exitCode = EXITCODE_RUNTIME_ERROR;
    }
}
 
Example 4
Source File: Bug421071Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
private Script compileScript() {
    String scriptSource = "importPackage(java.util);\n"
            + "var searchmon = 3;\n"
            + "var searchday = 10;\n"
            + "var searchyear = 2008;\n"
            + "var searchwkday = 0;\n"
            + "\n"
            + "var myDate = Calendar.getInstance();\n // this is a java.util.Calendar"
            + "myDate.set(Calendar.MONTH, searchmon);\n"
            + "myDate.set(Calendar.DATE, searchday);\n"
            + "myDate.set(Calendar.YEAR, searchyear);\n"
            + "searchwkday.value = myDate.get(Calendar.DAY_OF_WEEK);";
    Script script;
    Context context = factory.enterContext();
    try {
        script = context.compileString(scriptSource, "testScript", 1, null);
        return script;
    } finally {
        Context.exit();
    }
}
 
Example 5
Source File: Bug482203Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
public void testJavaApi() throws Exception {
    Context cx = RhinoAndroidHelper.prepareContext();
    try {
        cx.setOptimizationLevel(-1);
        Script script = cx.compileString(TestUtils.readAsset("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 6
Source File: Bug482203Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
public void testJsApi() throws Exception {
    Context cx = RhinoAndroidHelper.prepareContext();
    try {
        cx.setOptimizationLevel(-1);
        Script script = cx.compileString(TestUtils.readAsset("Bug482203.js"),
                "", 1, null);
        Scriptable scope = cx.initStandardObjects();
        script.exec(cx, scope);
        int counter = 0;
        for(;;)
        {
            Object cont = ScriptableObject.getProperty(scope, "c");
            if(cont == null)
            {
                break;
            }
            counter++;
            ((Callable)cont).call(cx, scope, scope, new Object[] { null });
        }
        assertEquals(counter, 5);
        assertEquals(Double.valueOf(3), ScriptableObject.getProperty(scope, "result"));
    } finally {
        Context.exit();
    }
}
 
Example 7
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.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 8
Source File: ContinuationsApiTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
public void testScriptWithNestedContinuations() {
    Context cx = Context.enter();
    try {
        cx.setOptimizationLevel(-1); // must use interpreter mode
        Script script = cx.compileString("myObject.g( myObject.f(1) ) + 2;",
                "test source", 1, null);
        cx.executeScriptWithContinuations(script, globalScope);
        fail("Should throw ContinuationPending");
    } catch (ContinuationPending pending) {
        try {
            Object applicationState = pending.getApplicationState();
            assertEquals(new Integer(1), 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(4), applicationState2);
            int saved2 = (Integer) applicationState2;
            Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 2);
            assertEquals(8, ((Number)result2).intValue());
        }
    } finally {
        Context.exit();
    }
}
 
Example 9
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 10
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 11
Source File: JsUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
static boolean check( String source, int lineNumber )
{
	Context cx = Context.enter( );

	Debugger oldDebugger = cx.getDebugger( );
	Object oldContext = cx.getDebuggerContextData( );
	boolean oldGenerate = cx.isGeneratingDebug( );
	int oldLevel = cx.getOptimizationLevel( );

	try
	{
		BreakableSourceChecker checker = new BreakableSourceChecker( );
		checker.lineNumber = lineNumber + 2;

		cx.setDebugger( checker, null );
		cx.setGeneratingDebug( true );
		cx.setOptimizationLevel( -1 );

		cx.compileString( addHeader( source ), "<check>", 1, null ); //$NON-NLS-1$

		return checker.breakable;
	}
	catch ( Exception e )
	{
		return false;
	}
	finally
	{
		cx.setDebugger( oldDebugger, oldContext );
		cx.setGeneratingDebug( oldGenerate );
		cx.setOptimizationLevel( oldLevel );

		Context.exit( );
	}
}
 
Example 12
Source File: DecompileTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * As of head of trunk on 30.09.09, decompile of "new Date()" returns "new Date" without parentheses.
 * @see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=519692">Bug 519692</a>
 */
@Test
public void newObject0Arg()
{
	final String source = "var x = new Date().getTime();";
	final ContextAction action = new ContextAction() {
		public Object run(final Context cx) {
			final Script script = cx.compileString(source, "my script", 0, null);
			Assert.assertEquals(source, cx.decompileScript(script, 4).trim());
			return null;
		}
	};
	Utils.runWithAllOptimizationLevels(action);
}
 
Example 13
Source File: ContinuationsApiTest.java    From astor with GNU General Public License v2.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 14
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 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: Main.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
static void processFileSecure(Context cx, Scriptable scope,
                              String path, Object securityDomain)
        throws IOException {

    boolean isClass = path.endsWith(".class");
    Object source = readFileOrUrl(path, !isClass);

    byte[] digest = getDigest(source);
    String key = path + "_" + cx.getOptimizationLevel();
    ScriptReference ref = scriptCache.get(key, digest);
    Script script = ref != null ? ref.get() : null;

    if (script == null) {
        if (isClass) {
            script = loadCompiledScript(cx, path, (byte[])source, securityDomain);
        } else {
            String strSrc = (String) source;
            // Support the executable script #! syntax:  If
            // the first line begins with a '#', treat the whole
            // line as a comment.
            if (strSrc.length() > 0 && strSrc.charAt(0) == '#') {
                for (int i = 1; i != strSrc.length(); ++i) {
                    int c = strSrc.charAt(i);
                    if (c == '\n' || c == '\r') {
                        strSrc = strSrc.substring(i);
                        break;
                    }
                }
            }
            script = cx.compileString(strSrc, path, 1, securityDomain);
        }
        scriptCache.put(key, digest, script);
    }

    if (script != null) {
        script.exec(cx, scope);
    }
}
 
Example 17
Source File: JavaScriptCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected String compileUnits(JRCompilationUnit[] units, String classpath,
		File tempDirFile) throws JRException
{
	Context context = ContextFactory.getGlobal().enterContext();
	try
	{
		Errors errors = new Errors();
		for (int i = 0; i < units.length; i++)
		{
			JRCompilationUnit unit = units[i];
			JavaScriptCompileData compileData = new JavaScriptCompileData();
			JRSourceCompileTask compileTask = unit.getCompileTask();
			for (Iterator<JRExpression> it = compileTask.getExpressions().iterator(); it.hasNext();)
			{
				JRExpression expr = it.next();
				int id = compileTask.getExpressionId(expr);
				
				ScriptExpressionVisitor defaultVisitor = defaultExpressionCreator();
				JRExpressionUtil.visitChunks(expr, defaultVisitor);
				String defaultExpression = defaultVisitor.getScript();
				
				//compile the default expression to catch syntax errors
				try
				{
					context.compileString(defaultExpression, "expression", 0, null);
				}
				catch (EvaluatorException e)
				{
					errors.addError(e);
				}

				if (!errors.hasErrors())
				{
					ScriptExpressionVisitor oldVisitor = oldExpressionCreator();
					ScriptExpressionVisitor estimatedVisitor = estimatedExpressionCreator();
					JRExpressionUtil.visitChunks(expr, new CompositeExpressionChunkVisitor(oldVisitor, estimatedVisitor));

					compileData.addExpression(id, defaultExpression, estimatedVisitor.getScript(), oldVisitor.getScript());
				}
			}
			
			if (!errors.hasErrors())
			{
				unit.setCompileData(compileData);
			}
		}
		
		return errors.errorMessage();
	}
	finally
	{
		Context.exit();
	}
}
 
Example 18
Source File: JavaScriptClassCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected String compileUnits(JRCompilationUnit[] units, String classpath,
		File tempDirFile) throws JRException
{
	Context context = ContextFactory.getGlobal().enterContext();
	try
	{
		JRPropertiesUtil properties = JRPropertiesUtil.getInstance(jasperReportsContext);
		int expressionsPerScript = properties.getIntegerProperty(PROPERTY_EXPRESSIONS_PER_SCRIPT);
		int scriptMaxLength = properties.getIntegerProperty(PROPERTY_SCRIPT_MAX_SIZE);
		
		int optimizationLevel = properties.getIntegerProperty(PROPERTY_OPTIMIZATION_LEVEL);
		context.setOptimizationLevel(optimizationLevel);
		context.getWrapFactory().setJavaPrimitiveWrap(false);

		Errors errors = new Errors();
		
		CompilerEnvirons compilerEnv = new CompilerEnvirons();
		compilerEnv.initFromContext(context);
		
		// we're using the context to compile the expressions in interpreted mode to catch syntax errors 
		context.setOptimizationLevel(-1);
		
		for (int i = 0; i < units.length; i++)
		{
			JRCompilationUnit unit = units[i];
			CompileSources compileSources = new CompileSources(expressionsPerScript, scriptMaxLength);
			JavaScriptCompiledData compiledData = new JavaScriptCompiledData();
			
			JRSourceCompileTask compileTask = unit.getCompileTask();
			for (Iterator<JRExpression> it = compileTask.getExpressions().iterator(); it.hasNext();)
			{
				JRExpression expr = it.next();
				int id = compileTask.getExpressionId(expr);
				
				ScriptExpressionVisitor defaultVisitor = defaultExpressionCreator();
				JRExpressionUtil.visitChunks(expr, defaultVisitor);
				String defaultExpression = defaultVisitor.getScript();
				
				//compile the default expression to catch syntax errors
				try
				{
					context.compileString(defaultExpression, "expression", 0, null);
				}
				catch (EvaluatorException e)
				{
					errors.addError(e);
				}

				if (!errors.hasErrors())
				{
					ScriptExpressionVisitor oldVisitor = oldExpressionCreator();
					ScriptExpressionVisitor estimatedVisitor = estimatedExpressionCreator();
					JRExpressionUtil.visitChunks(expr, new CompositeExpressionChunkVisitor(oldVisitor, estimatedVisitor));
					
					int defaultExpressionIdx = compileSources.addExpression(defaultExpression);
					int oldExpressionIdx = compileSources.addExpression(oldVisitor.getScript());
					int estimatedExpressionIdx = compileSources.addExpression(estimatedVisitor.getScript());
					
					compiledData.addExpression(id, defaultExpressionIdx, oldExpressionIdx, estimatedExpressionIdx);
				}
			}

			if (!errors.hasErrors())
			{
				compileScripts(unit, compilerEnv, compileSources, compiledData);
				unit.setCompileData(compiledData);
			}
		}

		return errors.errorMessage();
	}
	finally
	{
		Context.exit();
	}
}
 
Example 19
Source File: ExpressionLanguageJavaScriptImpl.java    From oval with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Script load(final String expression) {
   final Context ctx = ContextFactory.getGlobal().enterContext();
   ctx.setOptimizationLevel(9);
   return ctx.compileString(expression, "<cmd>", 1, null);
}
 
Example 20
Source File: RhinoScriptProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ScriptProcessor#execute(org.alfresco.service.cmr.repository.ScriptLocation, java.util.Map)
 */
public Object execute(ScriptLocation location, Map<String, Object> model)
{
    try
    {
        // test the cache for a pre-compiled script matching our path
        Script script = null;
        String path = location.getPath();
        if (this.compile && location.isCachable())
        {
            script = this.scriptCache.get(path);
        }
        if (script == null)
        {
            if (logger.isDebugEnabled())
                logger.debug("Resolving and compiling script path: " + path);
            
            // retrieve script content and resolve imports
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            FileCopyUtils.copy(location.getInputStream(), os);  // both streams are closed
            byte[] bytes = os.toByteArray();
            String source = new String(bytes, "UTF-8");
            source = resolveScriptImports(new String(bytes));
            
            // compile the script and cache the result
            Context cx = Context.enter();
            try
            {
                script = cx.compileString(source, location.toString(), 1, null);
                
                // We do not worry about more than one user thread compiling the same script.
                // If more than one request thread compiles the same script and adds it to the
                // cache that does not matter - the results will be the same. Therefore we
                // rely on the ConcurrentHashMap impl to deal both with ensuring the safety of the
                // underlying structure with asynchronous get/put operations and for fast
                // multi-threaded access to the common cache.
                if (this.compile && location.isCachable())
                {
                    this.scriptCache.put(path, script);
                }
            }
            finally
            {
                Context.exit();
            }
        }
        
        String debugScriptName = null;
        if (callLogger.isDebugEnabled())
        {
            int i = path.lastIndexOf('/');
            debugScriptName = (i != -1) ? path.substring(i+1) : path;
        }
        return executeScriptImpl(script, model, location.isSecure(), debugScriptName);
    }
    catch (Throwable err)
    {
        throw new ScriptException("Failed to execute script '" + location.toString() + "': " + err.getMessage(), err);
    }
}