Example usage for jdk.nashorn.internal.runtime Source sourceFor

List of usage examples for jdk.nashorn.internal.runtime Source sourceFor

Introduction

In this page you can find the example usage for jdk.nashorn.internal.runtime Source sourceFor.

Prototype

public static Source sourceFor(final String name, final Reader reader) throws IOException 

Source Link

Document

Returns an instance

Usage

From source file:com.mongodb.jvm.test.TestNashorn.java

License:Apache License

private static void run(String script) {
    PrintWriter out = new PrintWriter(System.out, true);
    PrintWriter err = new PrintWriter(System.err, true);
    Options options = new Options("nashorn", err);
    options.set("print.no.newline", true);
    ErrorManager errors = new ErrorManager(err);
    Context context = new Context(options, errors, out, err, Thread.currentThread().getContextClassLoader());
    ScriptObject globalScope = context.createGlobal();
    Context.setGlobal(globalScope);
    ScriptFunction fn = context.compileScript(Source.sourceFor(TestNashorn.class.getCanonicalName(), script),
            globalScope);//from w w w .j  av  a2s. co m
    ScriptRuntime.apply(fn, globalScope);
}

From source file:com.threecrickets.scripturian.adapter.NashornAdapter.java

License:LGPL

/**
 * Gets the Nashorn global scope associated with the execution context,
 * creating it if it doesn't exist. Each execution context is guaranteed to
 * have its own global scope.//www.j av  a 2s. c  om
 * 
 * @param executionContext
 *        The execution context
 * @return The global scope
 */
public ScriptObject getGlobalScope(ExecutionContext executionContext) {
    ScriptObject globalScope = (ScriptObject) executionContext.getAttributes().get(NASHORN_GLOBAL_SCOPE);

    boolean init = false;
    if (globalScope == null) {
        globalScope = context.createGlobal();
        executionContext.getAttributes().put(NASHORN_GLOBAL_SCOPE, globalScope);
        init = true;
    }

    Context.setGlobal(globalScope);

    // Define services as properties in scope
    globalScope.putAll(executionContext.getServices(), false);

    if (init) {
        ScriptFunction script = context.compileScript(
                Source.sourceFor(getClass().getCanonicalName() + ".getGlobalScope", INIT_SOURCE), globalScope);
        ScriptRuntime.apply(script, globalScope);
    }

    return globalScope;
}

From source file:com.threecrickets.scripturian.adapter.NashornProgram.java

License:LGPL

public void execute(ExecutionContext executionContext) throws ParsingException, ExecutionException {
    ScriptObject oldGlobal = Context.getGlobal();
    try {//from   www. ja v  a 2 s.c  o  m
        ScriptObject globalScope = adapter.getGlobalScope(executionContext);
        ErrorManager errorManager = adapter.context.getErrorManager();

        // long s = System.currentTimeMillis();
        ScriptFunction script = adapter.context
                .compileScript(Source.sourceFor(executable.getDocumentName(), sourceCode), globalScope);
        if ((script == null) || errorManager.hasErrors())
            throw new ParsingException(executable.getDocumentName());
        // s = System.currentTimeMillis() - s;
        // System.out.println( "COMPILE: " + s / 1000.0f );

        try {
            // s = System.currentTimeMillis();
            ScriptRuntime.apply(script, globalScope);
            // s = System.currentTimeMillis() - s;
            // System.out.println( "RUN: " + s / 1000.0f );
        } catch (Throwable x) {
            throw NashornAdapter.createExecutionException(x, executable.getDocumentName());
        } finally {
            adapter.context.getOut().flush();
            adapter.context.getErr().flush();
        }
    } finally {
        if (oldGlobal != null)
            Context.setGlobal(oldGlobal);
    }
}

From source file:IDE.SyntaxTree.JWebParser.java

public JWebParser(String source) {

    strSource = source;//from  www.  j  a v  a  2 s.  c  om

    Options opt = new Options("nashorn");
    opt.set("anon.functions", true);
    //   opt.set("parse.only", true);
    opt.set("scripting", true);

    Context context = new Context(opt, em, Thread.currentThread().getContextClassLoader());
    Context.setGlobal(new Global(context));
    Source textSource = Source.sourceFor("mySource", source);

    env = context.getEnv();//new ScriptEnvironment(opt, new PrintWriter(OutWriter), new PrintWriter(ErrorWriter) );

    nashornParser = new jdk.nashorn.internal.parser.Parser(env, textSource, em);

    // jdk.nashorn.internal.ir.FunctionCall

}

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

License:Open Source License

/**
 * Compiles the given script files in the command line
 *
 * @param context the nashorn context//from   ww  w.ja v a 2 s .  c  o  m
 * @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 ScriptObject global, final List<String> files)
        throws IOException {
    final ScriptObject 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, Source.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, Compiler.CompilationPhases.COMPILE_ALL_NO_INSTALL); //*/

            /*
            Compiler.forNoInstallerCompilation(context,
                functionNode.getSource(),
                env._strict | functionNode.isStrict()).
                compile(functionNode, Compiler.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;
}

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

License:Open Source License

/**
 * Runs the given JavaScript files in the command line
 *
 * @param context the nashorn context/*  ww w. j a v  a2  s.c o m*/
 * @param global the global scope
 * @param files the list of script files to run
 *
 * @return error code
 * @throws IOException when any script file read results in I/O error
 */
private int runScripts(final Context context, final ScriptObject global, final List<String> files)
        throws IOException {
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != global);
    try {
        if (globalChanged) {
            Context.setGlobal(global);
        }
        final ErrorManager errors = context.getErrorManager();

        // For each file on the command line.
        for (final String fileName : files) {
            if ("-".equals(fileName)) {
                final int res = readEvalPrint(context, global);
                if (res != SUCCESS) {
                    return res;
                }
                continue;
            }

            final File file = new File(fileName);
            final ScriptFunction script = context
                    .compileScript(Source.sourceFor(fileName, file.toURI().toURL()), global);
            if (script == null || errors.getNumberOfErrors() != 0) {
                return COMPILATION_ERROR;
            }

            try {
                apply(script, global);
            } catch (final NashornException e) {
                errors.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;
}

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

License:Open Source License

/**
 * read-eval-print loop for Nashorn shell.
 *
 * @param context the nashorn context//  w ww.  j  a v a  2  s  .c  o  m
 * @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;
}

From source file:org.netbeans.es.perftest.nashorn.NashornParser.java

License:Open Source License

@Override
public boolean parse(File file, ParserOptions options) throws IOException {
    final PrintWriter err = options.isPrintError() ? options.getProgressWriter()
            : new PrintWriter(new OutputStreamWriter(new ByteArrayOutputStream()));
    final ScriptEnvironment env = new ScriptEnvironment(
            new jdk.nashorn.internal.runtime.options.Options(file.getAbsolutePath()), err, err);
    final Source src = Source.sourceFor(file.getName(), file);
    final ErrorManager em = new ErrorManager(err);
    final Parser p = new Parser(env, src, em);
    final FunctionNode node = p.parse();
    return !em.hasErrors();
}