Search in sources :

Example 6 with Script

use of org.mozilla.javascript.Script in project hackpad by dropbox.

the class Main method processFileSecure.

static void processFileSecure(Context cx, Scriptable scope, String path, Object securityDomain) {
    boolean isClass = path.endsWith(".class");
    Object source = readFileOrUrl(path, !isClass);
    if (source == null) {
        exitCode = EXITCODE_FILE_NOT_FOUND;
        return;
    }
    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;
            // 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 = loadScriptFromSource(cx, strSrc, path, 1, securityDomain);
        }
        scriptCache.put(key, digest, script);
    }
    if (script != null) {
        evaluateScript(script, cx, scope);
    }
}
Also used : Script(org.mozilla.javascript.Script) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 7 with Script

use of org.mozilla.javascript.Script in project hackpad by dropbox.

the class Main method processSource.

/**
     * Evaluate JavaScript source.
     *
     * @param cx the current context
     * @param filename the name of the file to compile, or null
     *                 for interactive mode.
     */
public static void processSource(Context cx, String filename) {
    if (filename == null || filename.equals("-")) {
        PrintStream ps = global.getErr();
        if (filename == null) {
            // print implementation version
            ps.println(cx.getImplementationVersion());
        }
        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc == null) {
            charEnc = System.getProperty("file.encoding");
        }
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(global.getIn(), charEnc));
        } catch (UnsupportedEncodingException e) {
            throw new UndeclaredThrowableException(e);
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            if (filename == null)
                ps.print(prompts[0]);
            ps.flush();
            String source = "";
            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = in.readLine();
                } catch (IOException ioe) {
                    ps.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                ps.print(prompts[1]);
            }
            Script script = loadScriptFromSource(cx, source, "<stdin>", lineno, null);
            if (script != null) {
                Object result = evaluateScript(script, cx, global);
                // Avoid printing out undefined or function definitions.
                if (result != Context.getUndefinedValue() && !(result instanceof Function && source.trim().startsWith("function"))) {
                    try {
                        ps.println(Context.toString(result));
                    } catch (RhinoException rex) {
                        ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                    }
                }
                NativeArray h = global.history;
                h.put((int) h.getLength(), h, source);
            }
        }
        ps.println();
    } else if (filename.equals(mainModule)) {
        try {
            require.requireMain(cx, filename);
        } 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());
            exitCode = EXITCODE_RUNTIME_ERROR;
            Context.reportError(msg);
        }
    } else {
        processFile(cx, global, filename);
    }
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) PrintStream(java.io.PrintStream) Script(org.mozilla.javascript.Script) InputStreamReader(java.io.InputStreamReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Function(org.mozilla.javascript.Function) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) BufferedReader(java.io.BufferedReader) ScriptableObject(org.mozilla.javascript.ScriptableObject) RhinoException(org.mozilla.javascript.RhinoException)

Example 8 with Script

use of org.mozilla.javascript.Script in project hackpad by dropbox.

the class ContinuationsApiTest method testScriptWithNestedContinuations.

public void testScriptWithNestedContinuations() {
    Context cx = Context.enter();
    try {
        // must use interpreter mode
        cx.setOptimizationLevel(-1);
        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();
    }
}
Also used : Context(org.mozilla.javascript.Context) Script(org.mozilla.javascript.Script) ContinuationPending(org.mozilla.javascript.ContinuationPending)

Example 9 with Script

use of org.mozilla.javascript.Script in project hackpad by dropbox.

the class ContinuationsApiTest method testErrorOnEvalCall.

/**
   * 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 {
        // must use interpreter mode
        cx.setOptimizationLevel(-1);
        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();
    }
}
Also used : Context(org.mozilla.javascript.Context) Script(org.mozilla.javascript.Script) WrappedException(org.mozilla.javascript.WrappedException)

Example 10 with Script

use of org.mozilla.javascript.Script in project hackpad by dropbox.

the class GeneratedClassNameTest method doTest.

private void doTest(final String expectedName, final String scriptName) throws Exception {
    final Script script = (Script) ContextFactory.getGlobal().call(new ContextAction() {

        public Object run(final Context context) {
            return context.compileString("var f = 1", scriptName, 1, null);
        }
    });
    // remove serial number
    String name = script.getClass().getSimpleName();
    assertEquals(expectedName, name.substring(0, name.lastIndexOf('_')));
}
Also used : Context(org.mozilla.javascript.Context) Script(org.mozilla.javascript.Script) ContextAction(org.mozilla.javascript.ContextAction)

Aggregations

Script (org.mozilla.javascript.Script)17 Context (org.mozilla.javascript.Context)12 ScriptableObject (org.mozilla.javascript.ScriptableObject)5 IOException (java.io.IOException)3 InputStreamReader (java.io.InputStreamReader)3 ContinuationPending (org.mozilla.javascript.ContinuationPending)3 RhinoException (org.mozilla.javascript.RhinoException)3 Scriptable (org.mozilla.javascript.Scriptable)3 CompiledScript (javax.script.CompiledScript)2 ScriptContext (javax.script.ScriptContext)2 ScriptException (javax.script.ScriptException)2 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)2 ContextAction (org.mozilla.javascript.ContextAction)2 GeneratedClassLoader (org.mozilla.javascript.GeneratedClassLoader)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 BufferedReader (java.io.BufferedReader)1 PrintStream (java.io.PrintStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)1 MalformedURLException (java.net.MalformedURLException)1