Java Code Examples for org.mozilla.javascript.Script#exec()

The following examples show how to use org.mozilla.javascript.Script#exec() . 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: Main.java    From JsDroidCmd with Mozilla Public License 2.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 2
Source File: Bug482203Test.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testJsApi() 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();
        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 3
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 4
Source File: JavaScriptEvaluatorScope.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Object evaluateExpression(Script expression)
{
	ensureContext();
	
	Object value = expression.exec(context, scope);
	
	Object javaValue;
	// not converting Number objects because the generic conversion call below
	// always converts to Double
	if (value == null || value instanceof Number)
	{
		javaValue = value;
	}
	else
	{
		try
		{
			javaValue = Context.jsToJava(value, Object.class);
		}
		catch (EvaluatorException e)
		{
			throw new JRRuntimeException(e);
		}
	}
	return javaValue;
}
 
Example 5
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 6
Source File: DcEngineContext.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * JavaScriptファイルを解析し、オブジェクトに登録.
 * @param name JavaScriptソース名
 * @throws IOException IO例外
 */
private Object loadJs(final String name) throws IOException {
    URL path = getClass().getResource("/js-lib/" + name + ".js");

    Script jsBuildObject = null;
    if (engineLibCache.containsKey(path.toString())) {
        jsBuildObject = engineLibCache.get(path.toString());
    } else {
        FileInputStream fis = new FileInputStream(path.getFile());
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        jsBuildObject = cx.compileReader(isr, path.getPath(), 1, null);
        engineLibCache.put(path.toString(), jsBuildObject);
    }
    if (jsBuildObject == null) {
        return null;
    }
    Object ret = jsBuildObject.exec(cx, scope);
    log.debug("Load JavaScript from Local Resource : " + path);
    return ret;
}
 
Example 7
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 8
Source File: FunctionProviderBaseImpl.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Register script functions to scope.
 * 
 * @param cx
 * @param scope
 * @throws BirtException
 */
public void registerScriptFunction( Context cx, Scriptable scope )
		throws BirtException
{
	List<CategoryWrapper> wrapperedCategories = getWrapperedCategories( );
	for ( CategoryWrapper category : wrapperedCategories )
	{
		ScriptableObject.putProperty( scope,
				category.getClassName( ),
				category );
	}

	if ( !jarLibs.isEmpty( ) )
	{
		ClassLoader classLoader = cx.getApplicationClassLoader( );
		URLClassLoader scriptClassLoader = createScriptClassLoader( jarLibs,
				classLoader );
		setApplicationClassLoader( scriptClassLoader, cx );
	}
	for ( URL url : jsLibs )
	{
		Script script;
		try
		{
			script = cx.compileReader(
					new BufferedReader(
							new InputStreamReader( url.openStream( ) ) ),
					null,
					0,
					null );
			script.exec( cx, scope );
		}
		catch ( IOException e )
		{
		}
	}
}
 
Example 9
Source File: Require.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
private static void executeOptionalScript(Script script, Context cx,
        Scriptable executionScope)
{
    if(script != null) {
        script.exec(cx, executionScope);
    }
}
 
Example 10
Source File: JavascriptEngine.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public Object evaluate( ScriptContext scriptContext,
		ICompiledScript compiledScript ) throws BirtException
{
	assert ( compiledScript instanceof CompiledJavascript );
	// String source = ( (CompiledJavascript) compiledScript )
	// .getScriptText( );
	try
	{
		JavaScriptExecutionStatus.setExeucting(true);
		Script script = ( (CompiledJavascript) compiledScript )
				.getCompiledScript( );
		Object value = script.exec( context, getJSScope( scriptContext ) );
		return jsToJava( value );
	}
	catch ( Throwable e )
	{
		// Do not include javascript source code
		// throw new CoreException(
		// ResourceConstants.JAVASCRIPT_COMMON_ERROR,
		// new Object[]{source, e.getMessage( )}, e );
		throw new CoreException( ResourceConstants.INVALID_EXPRESSION,
				e.getMessage( ),
				e );
	}finally {
		JavaScriptExecutionStatus.remove();
	}
}
 
Example 11
Source File: ProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Object[] compileScript(Context cx, String scriptStr, Scriptable scriptScope, File f) {
    int opt = cx.getOptimizationLevel();
    cx.setOptimizationLevel(-1);
    Script script = cx.compileString(scriptStr, f.getName(), 1, null);
    script.exec(cx, scriptScope);
    Object[] ids = scriptScope.getIds();
    cx.setOptimizationLevel(opt);
    script = cx.compileString(scriptStr, f.getName(), 1, null);
    script.exec(cx, scriptScope);
    return ids;
}
 
Example 12
Source File: Bug714204Test.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_assign_this() {
    StringBuilder sb = new StringBuilder();
    sb.append("function F() {\n");
    sb.append("  [this.x] = arguments;\n");
    sb.append("}\n");
    sb.append("var f = new F('a');\n");
    sb.append("(f.x == 'a')\n");
    Script script = cx.compileString(sb.toString(), "<eval>", 1, null);
    Object result = script.exec(cx, scope);
    assertEquals(Boolean.TRUE, result);
}
 
Example 13
Source File: Require.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static void executeOptionalScript(Script script, Context cx,
        Scriptable executionScope)
{
    if(script != null) {
        script.exec(cx, executionScope);
    }
}
 
Example 14
Source File: Main.java    From astor with GNU General Public License v2.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 15
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 16
Source File: Bug714204Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Test
public void test_assign_this() {
    StringBuilder sb = new StringBuilder();
    sb.append("function F() {\n");
    sb.append("  [this.x] = arguments;\n");
    sb.append("}\n");
    sb.append("var f = new F('a');\n");
    sb.append("(f.x == 'a')\n");
    Script script = cx.compileString(sb.toString(), "<eval>", 1, null);
    Object result = script.exec(cx, scope);
    assertEquals(Boolean.TRUE, result);
}
 
Example 17
Source File: Issue176Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
public void testThrowing() throws Exception {
    cx = RhinoAndroidHelper.prepareContext();
    try {
        Script script = cx.compileString(TestUtils.readAsset("Issue176.js"),
                "Issue176.js", 1, null);
        scope = cx.initStandardObjects();
        scope.put("host", scope, this);
        script.exec(cx, scope); // calls our methods
    } finally {
        Context.exit();
    }
}
 
Example 18
Source File: CaliperSpiderBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runBenchmark(String name, int iterations)
{
    Script s = scripts.get(name);
    for (int i = 0; i < iterations; i++) {
        s.exec(cx, scope);
    }
}
 
Example 19
Source File: JavascriptEvalUtil.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This method will not convert the data of return value, so it might the
 * Java data type or that of Java Script.
 * 
 * @param cx
 * @param scope
 * @param scriptText
 * @param source
 * @param lineNo
 * @return the evaluated value
 * @throws BirtException
 */
public static Object evaluateRawScript(Context cx, Scriptable scope,
		String scriptText, String source, int lineNo)
		throws BirtException
{
	Object result = null;

	// Use provided context, or get the thread context if none provided
	boolean enterContext = cx == null;
	if ( enterContext )
		cx = Context.enter();
	
	try
	{
		Script compiledScript = getCompiledScript( cx, scope,
				scriptText,
				source,
				lineNo );
		result = compiledScript.exec( cx, scope );
	}
	catch ( RhinoException e)
	{
		// Note: use the real source and lineNo here. The source and lineNo reported
		// by e can be wrong, since we may be executing an identical compiled script
		// from a different source/line
		throw wrapRhinoException( e, scriptText, source, lineNo );
	}
	finally
	{
		if ( enterContext)
			Context.exit();
	}
	
	return result;
}
 
Example 20
Source File: TransformEngineImpl.java    From p3-batchrefine with Apache License 2.0 4 votes vote down vote up
/**
     * This method runs part of the core module controller.js script so that we
     * can register all operations without having to duplicate configuration
     * here.
     */

    public void loadModule(String name, String path, String... initFunctions)
            throws IOException {

        ButterflyModule core = new ButterflyModuleStub(name);
//        File controllerFile = new File(Configurations.get("refine.root",
//                "../OpenRefine"), path);

        String script = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(path));

        if (script == null) {
            fLogger.warn(String.format(
                    "Can't find controller script for module %s at %s -- "
                            + "module may not work as expected.", name,
                    name));
            return;
        }

        // Compiles and "executes" the controller script. The script basically
        // contains function declarations.
        Context context = ContextFactory.getGlobal().enterContext();
        Script controller = context.compileString(
                script, "init.js", 1, null);

        // Initializes the scope.
        ScriptableObject scope = new ImporterTopLevel(context);

        scope.put("module", scope, core);
        controller.exec(context, scope);

        for (String function : initFunctions) {
            // Runs the function that initializes the OperationRegistry.
            try {
                Object fun = context.compileString(function, null, 1, null)
                        .exec(context, scope);
                if (fun != null && fun instanceof Function) {
                    ((Function) fun).call(context, scope, scope,
                            new Object[]{});
                }
            } catch (EcmaError ex) {
                fLogger.error("Error running controller script.", ex);
            }
        }
    }