Example usage for jdk.nashorn.internal.objects Global setScriptContext

List of usage examples for jdk.nashorn.internal.objects Global setScriptContext

Introduction

In this page you can find the example usage for jdk.nashorn.internal.objects Global setScriptContext.

Prototype

public void setScriptContext(final ScriptContext ctxt) 

Source Link

Document

Set the current script context

Usage

From source file:org.kihara.util.JavascriptEngine.java

License:Open Source License

/**
 * Run method logic.//  ww  w  . ja v a2  s . c  om
 *
 * @param in input stream for Shell
 * @param out output stream for Shell
 * @param err error stream for Shell
 *
 * @return exit code
 *
 * @throws IOException if there's a problem setting up the streams
 */
protected final int run(final InputStream in, final OutputStream out, final OutputStream err)
        throws IOException {
    final Context context = makeContext(in, out, err);
    if (context == null) {
        return COMMANDLINE_ERROR;
    }

    final ScriptObject global = context.createGlobal();
    final ScriptEnvironment env = context.getEnv();
    final List<String> files = env.getFiles();

    // Prepare bindings here.
    SimpleScriptContext scriptContext = new SimpleScriptContext();
    ScriptObjectMirror mirror = (ScriptObjectMirror) ScriptObjectMirror.wrap(global, global);
    scriptContext.setBindings(mirror, ScriptContext.ENGINE_SCOPE);
    bindings.accept(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE));

    // TODO: JDK 1.8u65 method only. Will invoke old call if fails.
    try {
        Global g = ((Global) global);
        ScriptEngine s = new ScriptEngineManager().getEngineByName("nashorn");

        try {
            Method m = Global.class.getMethod("initBuiltinObjects", ScriptEngine.class, ScriptContext.class);
            m.invoke(g, s, scriptContext);
        } catch (NoSuchMethodException e) {
            try {
                Method m = Global.class.getMethod("initBuiltinObjects", ScriptEngine.class);
                m.invoke(g, s);
                g.setScriptContext(scriptContext);
            } catch (NoSuchMethodException ee) {
                System.err.println("COULD NOT INIT!");
                throw new IOException("COULD NOT INIT!");
            }
        }
    } catch (Exception ignored) {
    }

    if (files.isEmpty()) {
        return readEvalPrint(context, global);
    }

    if (env._compile_only) {
        return compileScripts(context, global, files);
    }

    if (env._fx) {
        return runFXScripts(context, global, files);
    }

    return runScripts(context, global, files);
}