List of usage examples for jdk.nashorn.internal.runtime Context setGlobal
public static void setGlobal(final Global global)
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 a v a2 s . c o m ScriptRuntime.apply(fn, globalScope); }
From source file:com.siemens.ct.exi.javascript.JStoAST.java
License:Open Source License
public static String getAST(String jsCode) throws IOException, EXIException { // http://sites.psu.edu/robertbcolton/2015/07/31/java-8-nashorn-script-engine/ /*/*from w w w .j av a 2s .c om*/ * This JSON encoding provided by Nashorn is compliant with the * community standard JavaScript JSON AST model popularized by Mozilla. * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/ * SpiderMonkey/Parser_API */ // Additionally the OpenJDK project is developing a public interface for // Java 9 that allows AST traversal in a more standard and user friendly // way. // String code = "function a() { var b = 5; } function c() { }"; // String sin = "./data//jquery.min.js"; // String sin = "./data/animals.js"; // String code = new String(Files.readAllBytes(Paths.get(sin))); // ScriptEngine engine = new // ScriptEngineManager().getEngineByName("nashorn"); // engine.eval("print('Hello World!');"); // load jquery source file // engine.eval("load('" + // "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" + // "');"); // engine.eval("load('" + sin + "');"); Options options = new Options("nashorn"); options.set("anon.functions", true); options.set("parse.only", true); options.set("scripting", true); ErrorManager errors = new ErrorManager(); Context contextm = new Context(options, errors, Thread.currentThread().getContextClassLoader()); Context.setGlobal(contextm.createGlobal()); String jsonAST = ScriptUtils.parse(jsCode, "<unknown>", false); return jsonAST; }
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.//from www . j a v a2 s . co m * * @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.NashornAdapter.java
License:LGPL
@Override public Object enter(String entryPointName, Executable executable, ExecutionContext executionContext, Object... arguments) throws NoSuchMethodException, ParsingException, ExecutionException { ScriptObject oldGlobal = Context.getGlobal(); try {/*from w w w. java2 s . co m*/ ScriptObject globalScope = getGlobalScope(executionContext); Object entryPoint = globalScope.get(entryPointName); if (!(entryPoint instanceof ScriptFunction)) throw new NoSuchMethodException(entryPointName); try { ScriptFunction function = (ScriptFunction) entryPoint; Object r = ScriptRuntime.apply(function, null, arguments); if (r instanceof NativeArray) r = NativeJava.to(null, r, "java.util.List"); return r; } catch (ClassNotFoundException x) { throw new ExecutionException(executable.getDocumentName(), x); } catch (Throwable x) { throw createExecutionException(x, executable.getDocumentName()); } finally { context.getOut().flush(); context.getErr().flush(); } } finally { if (oldGlobal != null) Context.setGlobal(oldGlobal); } }
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 ww w. ja va 2 s .c om*/ 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;/* w w w . j a va 2s .co m*/ 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:io.stallion.plugins.javascript.JavascriptShell.java
License:Open Source License
private static int readEvalPrint(InputStream input, OutputStream out, Context context, Global global) throws IOException, ScriptException { JsPluginSettings pluginSettings = new JsPluginSettings(); //context.eval(global, ""); //Global global = context.createGlobal(); //ScriptEnvironment env = context.getEnv(); String prompt = bundle.getString("shell.prompt"); //BufferedReader in = new BufferedReader(new InputStreamReader(input)); ConsoleReader in = new ConsoleReader(); PrintWriter err = context.getErr(); Global oldGlobal = Context.getGlobal(); boolean globalChanged = oldGlobal != global; ScriptEnvironment env = context.getEnv(); if (DB.available()) { global.put("DB", DB.instance(), false); }//from w w w.ja v a2 s .c om try { if (globalChanged) { Context.setGlobal(global); } global.addShellBuiltins(); // Load builtins global.put("javaToJsHelpers", new JavaToJsHelpers(Sandbox.allPermissions()), true); SandboxedContext ctx = new SandboxedContext(Settings.instance().getTargetFolder() + "/js", Sandbox.allPermissions(), pluginSettings); global.put("myContext", ctx, true); String stallionSharedJs = IOUtils .toString(JavascriptShell.class.getResource("/jslib/stallion_shared.js"), UTF8); context.eval(global, "load(" + JSON.stringify( map(val("script", stallionSharedJs), val("name", "stallion_shared.js"))) + ");", global, "<shellboot>"); global.put("stallionClassLoader", new UnrestrictedJsClassLoader(), true); while (true) { String source; do { //err.print(prompt); //err.flush(); source = ""; try { source = in.readLine(prompt); } catch (IOException var14) { err.println(var14.toString()); } if (source == null) { return 0; } } while (source.isEmpty()); try { Object e = context.eval(global, source, global, "<shell>"); if (e != ScriptRuntime.UNDEFINED) { err.println(JSType.toString(e)); } } catch (Exception var15) { err.println(var15); if (env._dump_on_error) { var15.printStackTrace(err); } } } } finally { if (globalChanged) { Context.setGlobal(oldGlobal); } } }
From source file:me.finalchild.nashornbukkit.util.BukkitImporter.java
License:MIT License
public static Set<String> getUsedIdentifiers(Path file) throws IOException { Set<String> result = new HashSet<>(); String text = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); String json;// www.j av a 2s .co m Options options = new Options(""); ErrorManager errorManager = new ErrorManager(); Context context = new Context(options, errorManager, NashornBukkit.class.getClassLoader()); Context.setGlobal(context.createGlobal()); json = ScriptUtils.parse(text, file.getFileName().toString(), false); JsonParser jsonParser = new JsonParser(); JsonObject rootObj = jsonParser.parse(json).getAsJsonObject(); addUsedIdentifiers(rootObj, result); return result; }
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 . j a v a2 s . c om * @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/*from w w w. j a v a 2 s. co 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; }