Java Code Examples for jdk.nashorn.internal.runtime.Context#setGlobal()

The following examples show how to use jdk.nashorn.internal.runtime.Context#setGlobal() . 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: NashornScriptEngine.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 2
Source File: ContextTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalTest() {
    final Options options = new Options("");
    final ErrorManager errors = new ErrorManager();
    final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    final Global oldGlobal = Context.getGlobal();
    Context.setGlobal(cx.createGlobal());
    try {
        String code = "22 + 10";
        assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue());

        code = "obj = { js: 'nashorn' }; obj.js";
        assertEquals(eval(cx, "<evalTest2>", code), "nashorn");
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example 3
Source File: NashornScriptEngine.java    From nashorn with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        // set ScriptContext variables if ctxt is non-null
        if (ctxt != null) {
            setContextVariables(ctxtGlobal, ctxt);
        }
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 4
Source File: ContextTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void evalTest() {
    final Options options = new Options("");
    final ErrorManager errors = new ErrorManager();
    final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    final Global oldGlobal = Context.getGlobal();
    Context.setGlobal(cx.createGlobal());
    try {
        String code = "22 + 10";
        assertTrue(32.0 == ((Number)(eval(cx, "<evalTest>", code))).doubleValue());

        code = "obj = { js: 'nashorn' }; obj.js";
        assertEquals(eval(cx, "<evalTest2>", code), "nashorn");
    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example 5
Source File: NashornScriptEngine.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        // set ScriptContext variables if ctxt is non-null
        if (ctxt != null) {
            setContextVariables(ctxtGlobal, ctxt);
        }
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 6
Source File: ScriptObjectMirror.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object newObject(final Object... args) {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        if (sobj instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
            return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
        }

        throw new RuntimeException("not a constructor: " + toString());
    } catch (final NashornException ne) {
        throw ne.initEcmaError(global);
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 7
Source File: ScriptObjectMirror.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Call member function
 * @param functionName function name
 * @param args         arguments
 * @return return value of function
 */
public Object callMember(final String functionName, final Object... args) {
    Objects.requireNonNull(functionName);
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        final Object val = sobj.get(functionName);
        if (val instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
            return wrapLikeMe(ScriptRuntime.apply((ScriptFunction)val, sobj, unwrapArray(modArgs, global)));
        } else if (val instanceof JSObject && ((JSObject)val).isFunction()) {
            return ((JSObject)val).call(sobj, args);
        }

        throw new NoSuchMethodException("No such function " + functionName);
    } catch (final NashornException ne) {
        throw ne.initEcmaError(global);
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 8
Source File: NashornScriptEngine.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 9
Source File: Shell.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Runs launches "fx:bootstrap.js" with the given JavaScript files provided
 * as arguments.
 *
 * @param context the nashorn context
 * @param global the global scope
 * @param files the list of script files to provide
 *
 * @return error code
 * @throws IOException when any script file read results in I/O error
 */
private static int runFXScripts(final Context context, final Global global, final List<String> files) throws IOException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        global.addOwnProperty("$GLOBAL", Property.NOT_ENUMERABLE, global);
        global.addOwnProperty("$SCRIPTS", Property.NOT_ENUMERABLE, files);
        context.load(global, "fx:bootstrap.js");
    } catch (final NashornException e) {
        context.getErrorManager().error(e.toString());
        if (context.getEnv()._dump_on_error) {
            e.printStackTrace(context.getErr());
        }

        return RUNTIME_ERROR;
    } finally {
        context.getOut().flush();
        context.getErr().flush();
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return SUCCESS;
}
 
Example 10
Source File: NashornScriptEngine.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private CompiledScript asCompiledScript(final Source source) throws ScriptException {
    final Context.MultiGlobalCompiledScript mgcs;
    final ScriptFunction func;
    final Global oldGlobal = Context.getGlobal();
    final Global newGlobal = getNashornGlobalFrom(context);
    final boolean globalChanged = (oldGlobal != newGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(newGlobal);
        }

        mgcs = nashornContext.compileScript(source);
        func = mgcs.getFunction(newGlobal);
    } catch (final Exception e) {
        throwAsScriptException(e, newGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return new CompiledScript() {
        @Override
        public Object eval(final ScriptContext ctxt) throws ScriptException {
            final Global globalObject = getNashornGlobalFrom(ctxt);
            // Are we running the script in the same global in which it was compiled?
            if (func.getScope() == globalObject) {
                return evalImpl(func, ctxt, globalObject);
            }

            // different global
            return evalImpl(mgcs, ctxt, globalObject);
        }
        @Override
        public ScriptEngine getEngine() {
            return NashornScriptEngine.this;
        }
    };
}
 
Example 11
Source File: JavaAdapterServices.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the current global scope to that of the adapter global
 * @param adapterGlobal the adapter's global scope
 * @return a Runnable that when invoked restores the previous global
 */
public static Runnable setGlobal(final ScriptObject adapterGlobal) {
    final Global currentGlobal = Context.getGlobal();
    if (adapterGlobal != currentGlobal) {
        Context.setGlobal(adapterGlobal);
        return ()->Context.setGlobal(currentGlobal);
    }
    return ()->{};
}
 
Example 12
Source File: ScriptObjectMirror.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object newObject(final Object... args) {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        if (sobj instanceof ScriptFunction) {
            final Object[] modArgs = globalChanged? wrapArrayLikeMe(args, oldGlobal) : args;
            return wrapLikeMe(ScriptRuntime.construct((ScriptFunction)sobj, unwrapArray(modArgs, global)));
        }

        throw new RuntimeException("not a constructor: " + toString());
    } catch (final NashornException ne) {
        throw ne.initEcmaError(global);
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example 13
Source File: Shell.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Compiles the given script files in the command line
 * This is called only when using the --compile-only flag
 *
 * @param context the nashorn context
 * @param global the global scope
 * @param files the list of script files to compile
 *
 * @return error code
 * @throws IOException when any script file read results in I/O error
 */
private static int compileScripts(final Context context, final Global global, final List<String> files) throws IOException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    final ScriptEnvironment env = context.getEnv();
    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }
        final ErrorManager errors = context.getErrorManager();

        // For each file on the command line.
        for (final String fileName : files) {
            final FunctionNode functionNode = new Parser(env, sourceFor(fileName, new File(fileName)), errors, env._strict, 0, context.getLogger(Parser.class)).parse();

            if (errors.getNumberOfErrors() != 0) {
                return COMPILATION_ERROR;
            }

            new Compiler(
                   context,
                   env,
                   null, //null - pass no code installer - this is compile only
                   functionNode.getSource(),
                   context.getErrorManager(),
                   env._strict | functionNode.isStrict()).
                   compile(functionNode, CompilationPhases.COMPILE_ALL_NO_INSTALL);

            if (env._print_ast) {
                context.getErr().println(new ASTWriter(functionNode));
            }

            if (env._print_parse) {
                context.getErr().println(new PrintVisitor(functionNode));
            }

            if (errors.getNumberOfErrors() != 0) {
                return COMPILATION_ERROR;
            }
        }
    } finally {
        env.getOut().flush();
        env.getErr().flush();
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return SUCCESS;
}
 
Example 14
Source File: ContextTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void reflectionTest() {
    final Options options = new Options("");
    final ErrorManager errors = new ErrorManager();
    final Context cx = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    final boolean strict = cx.getEnv()._strict;
    final Global oldGlobal = Context.getGlobal();
    Context.setGlobal(cx.createGlobal());

    try {
        final String code = "var obj = { x: 344, y: 42 }";
        eval(cx, "<reflectionTest>", code);

        final Object obj = Context.getGlobal().get("obj");

        assertTrue(obj instanceof ScriptObject);

        final ScriptObject sobj = (ScriptObject)obj;
        int count = 0;
        for (final Map.Entry<?, ?> ex : sobj.entrySet()) {
            final Object key = ex.getKey();
            if (key.equals("x")) {
                assertTrue(ex.getValue() instanceof Number);
                assertTrue(344.0 == ((Number)ex.getValue()).doubleValue());

                count++;
            } else if (key.equals("y")) {
                assertTrue(ex.getValue() instanceof Number);
                assertTrue(42.0 == ((Number)ex.getValue()).doubleValue());

                count++;
            }
        }
        assertEquals(count, 2);
        assertEquals(sobj.size(), 2);

        // add property
        sobj.put("zee", "hello", strict);
        assertEquals(sobj.get("zee"), "hello");
        assertEquals(sobj.size(), 3);

    } finally {
        Context.setGlobal(oldGlobal);
    }
}
 
Example 15
Source File: CompilerTest.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private void compileJSFile(final File file, final TestFilter filter) {
    if (VERBOSE) {
        log("Begin compiling " + file.getAbsolutePath());
    }

    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        final char[] buffer = Source.readFully(file);
        boolean excluded = false;

        if (filter != null) {
            final String content = new String(buffer);
            excluded = filter.exclude(file, content);
        }

        if (excluded) {
            if (VERBOSE) {
                log("Skipping " + file.getAbsolutePath());
            }
            skipped++;
            return;
        }

        if (globalChanged) {
            Context.setGlobal(global);
        }
        final Source source = new Source(file.getAbsolutePath(), buffer);
        final ScriptFunction script = context.compileScript(source, global);
        if (script == null || context.getErrorManager().getNumberOfErrors() > 0) {
            log("Compile failed: " + file.getAbsolutePath());
            failed++;
        } else {
            passed++;
        }
    } catch (final Throwable t) {
        log("Compile failed: " + file.getAbsolutePath() + " : " + t);
        if (VERBOSE) {
            t.printStackTrace(System.out);
        }
        failed++;
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    if (VERBOSE) {
        log("Done compiling " + file.getAbsolutePath());
    }
}
 
Example 16
Source File: Shell.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * read-eval-print loop for Nashorn shell.
 *
 * @param context the nashorn context
 * @param global  global scope object to use
 * @return return code
 */
private static int readEvalPrint(final Context context, final Global global) {
    final String prompt = bundle.getString("shell.prompt");
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    final PrintWriter err = context.getErr();
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    final ScriptEnvironment env = context.getEnv();

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        global.addShellBuiltins();

        while (true) {
            err.print(prompt);
            err.flush();

            String source = "";
            try {
                source = in.readLine();
            } catch (final IOException ioe) {
                err.println(ioe.toString());
            }

            if (source == null) {
                break;
            }

            if (source.isEmpty()) {
                continue;
            }

            try {
                final Object res = context.eval(global, source, global, "<shell>");
                if (res != ScriptRuntime.UNDEFINED) {
                    err.println(JSType.toString(res));
                }
            } catch (final Exception e) {
                err.println(e);
                if (env._dump_on_error) {
                    e.printStackTrace(err);
                }
            }
        }
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return SUCCESS;
}
 
Example 17
Source File: CompilerTest.java    From jdk8u_nashorn with GNU General Public License v2.0 4 votes vote down vote up
private void compileJSFile(final File file, final TestFilter filter) {
    if (VERBOSE) {
        log("Begin compiling " + file.getAbsolutePath());
    }

    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        final char[] buffer = readFully(file);
        boolean excluded = false;

        if (filter != null) {
            final String content = new String(buffer);
            excluded = filter.exclude(file, content);
        }

        if (excluded) {
            if (VERBOSE) {
                log("Skipping " + file.getAbsolutePath());
            }
            skipped++;
            return;
        }

        if (globalChanged) {
            Context.setGlobal(global);
        }
        final Source source = sourceFor(file.getAbsolutePath(), buffer);
        final ScriptFunction script = context.compileScript(source, global);
        if (script == null || context.getErrorManager().getNumberOfErrors() > 0) {
            log("Compile failed: " + file.getAbsolutePath());
            failed++;
        } else {
            passed++;
        }
    } catch (final Throwable t) {
        log("Compile failed: " + file.getAbsolutePath() + " : " + t);
        if (VERBOSE) {
            t.printStackTrace(System.out);
        }
        failed++;
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    if (VERBOSE) {
        log("Done compiling " + file.getAbsolutePath());
    }
}
 
Example 18
Source File: Shell.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * read-eval-print loop for Nashorn shell.
 *
 * @param context the nashorn context
 * @param global  global scope object to use
 * @return return code
 */
private static int readEvalPrint(final Context context, final Global global) {
    final String prompt = bundle.getString("shell.prompt");
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    final PrintWriter err = context.getErr();
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    final ScriptEnvironment env = context.getEnv();

    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }

        global.addShellBuiltins();

        while (true) {
            err.print(prompt);
            err.flush();

            String source = "";
            try {
                source = in.readLine();
            } catch (final IOException ioe) {
                err.println(ioe.toString());
            }

            if (source == null) {
                break;
            }

            if (source.isEmpty()) {
                continue;
            }

            try {
                final Object res = context.eval(global, source, global, "<shell>");
                if (res != ScriptRuntime.UNDEFINED) {
                    err.println(JSType.toString(res));
                }
            } catch (final Exception e) {
                err.println(e);
                if (env._dump_on_error) {
                    e.printStackTrace(err);
                }
            }
        }
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    return SUCCESS;
}
 
Example 19
Source File: CompilerTest.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void compileJSFile(final File file, final TestFilter filter) {
    if (VERBOSE) {
        log("Begin compiling " + file.getAbsolutePath());
    }

    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);

    try {
        final char[] buffer = readFully(file);
        boolean excluded = false;

        if (filter != null) {
            final String content = new String(buffer);
            excluded = filter.exclude(file, content);
        }

        if (excluded) {
            if (VERBOSE) {
                log("Skipping " + file.getAbsolutePath());
            }
            skipped++;
            return;
        }

        if (globalChanged) {
            Context.setGlobal(global);
        }
        final Source source = sourceFor(file.getAbsolutePath(), buffer);
        final ScriptFunction script = context.compileScript(source, global);
        if (script == null || context.getErrorManager().getNumberOfErrors() > 0) {
            log("Compile failed: " + file.getAbsolutePath());
            failed++;
        } else {
            passed++;
        }
    } catch (final Throwable t) {
        log("Compile failed: " + file.getAbsolutePath() + " : " + t);
        if (VERBOSE) {
            t.printStackTrace(System.out);
        }
        failed++;
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }

    if (VERBOSE) {
        log("Done compiling " + file.getAbsolutePath());
    }
}
 
Example 20
Source File: JavaAdapterServices.java    From hottub with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Set the current global scope
 * @param global the global scope
 */
public static void setGlobal(final Object global) {
    Context.setGlobal((ScriptObject)global);
}