Example usage for jdk.nashorn.internal.runtime Context eval

List of usage examples for jdk.nashorn.internal.runtime Context eval

Introduction

In this page you can find the example usage for jdk.nashorn.internal.runtime Context eval.

Prototype

public Object eval(final ScriptObject initialScope, final String string, final Object callThis,
        final Object location, final boolean strict, final boolean evalCall) 

Source Link

Document

Entry point for eval

Usage

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

License:Open Source License

/**
 * read-eval-print loop for Nashorn shell.
 *
 * @param context the nashorn context/*from ww  w. j  av  a2 s  .  com*/
 * @param global  global scope object to use
 * @return return code
 */
@SuppressWarnings("resource")
private static int readEvalPrint(final Context context, final ScriptObject global) {
    final String prompt = "> ";//bundle.getString("shell.prompt");
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    final PrintWriter err = context.getErr();
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    final ScriptEnvironment env = context.getEnv();

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

        // initialize with "shell.js" script
        try {
            final Source source = Source.sourceFor("<shell.js>", JavascriptEngine.SHELL_INIT_JS);
            context.eval(global, source.getString(), global, "<shell.js>", false, false);

            // custom scripts
            context.eval(global, script.get(), global, "<shell.js>", false, false);
        } catch (final Exception e) {
            err.println(e);
            if (env._dump_on_error) {
                e.printStackTrace(err);
            }

            return INTERNAL_ERROR;
        }

        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;
            }

            Object res;
            try {
                res = context.eval(global, source, global, "<shell>", env._strict, false);
            } catch (final Exception e) {
                err.println(e);
                if (env._dump_on_error) {
                    e.printStackTrace(err);
                }
                continue;
            }

            if (res != ScriptRuntime.UNDEFINED) {
                err.println(JSType.toString(res));
            }
        }
    } finally {
        if (globalChanged) {
            Context.setGlobal(global);
        }
    }

    return SUCCESS;
}