Example usage for jdk.nashorn.internal.runtime ScriptRuntime safeToString

List of usage examples for jdk.nashorn.internal.runtime ScriptRuntime safeToString

Introduction

In this page you can find the example usage for jdk.nashorn.internal.runtime ScriptRuntime safeToString.

Prototype

public static String safeToString(final Object obj) 

Source Link

Document

This is called whenever runtime wants to throw an error and wants to provide meaningful information about an object.

Usage

From source file:z.zee.Z.java

License:Open Source License

/**
 * read-eval-print loop for Nashorn shell.
 *
 * @param context the nashorn context//  ww  w. j  a  v a2s  . c om
 * @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 "z.js" script
        try {
            final Source source = new Source("<z.js>", Z.class.getResource("resources/z.js"));
            context.eval(global, source.getString(), global, "<z.js>", 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;
            }

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

            if (res != null && res != ScriptRuntime.UNDEFINED) {
                err.println(ScriptRuntime.safeToString(res));
            }
        }
    } finally {
        if (globalChanged) {
            Context.setGlobal(global);
        }
    }

    return SUCCESS;
}