List of usage examples for jdk.nashorn.internal.runtime Context getGlobal
public static Global getGlobal()
From source file:com.threecrickets.jvm.json.nashorn.ScriptObjectMirrorEncoder.java
License:Mozilla Public License
public void encode(Object object, JsonContext context) throws IOException { ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) object; Object wrapped = ScriptObjectMirror.unwrap(scriptObjectMirror, Context.getGlobal()); if (!(wrapped instanceof ScriptObjectMirror)) { context.encode(wrapped);/*from w w w .j ava 2s .c o m*/ return; } if (scriptObjectMirror.isArray()) { context.out.append('['); int length = scriptObjectMirror.size(); if (length > 0) { context.newline(); for (int i = 0; i < length; i++) { Object value = scriptObjectMirror.getSlot(i); context.indentNested(); context.nest().encode(value); if (i < length - 1) context.comma(); } context.newline(); context.indent(); } context.out.append(']'); } else { context.out.append('{'); String[] keys = scriptObjectMirror.getOwnKeys(true); int length = keys.length; if (length > 0) { context.newline(); for (int i = 0; i < length; i++) { String key = keys[i]; Object value = scriptObjectMirror.get(key); context.indentNested(); context.quoted(key); context.colon(); context.nest().encode(value); if (i < length - 1) context.comma(); } context.newline(); context.indent(); } context.out.append('}'); } }
From source file:com.threecrickets.jvm.json.nashorn.ScriptObjectMirrorTransformer.java
License:Mozilla Public License
public Object transform(Object object, JsonImplementation implementation) { if (object instanceof ScriptObjectMirror) { ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) object; Object wrapped = ScriptObjectMirror.unwrap(scriptObjectMirror, Context.getGlobal()); if (!(wrapped instanceof ScriptObjectMirror)) { for (JsonTransformer transformer : implementation.getTransformers()) { Object r = transformer.transform(wrapped, implementation); if (r != null) return r; }//from w w w .ja va 2 s . c o m } } return null; }
From source file:com.threecrickets.jvm.json.nashorn.util.NashornNativeUtil.java
License:Mozilla Public License
public static Object unwrap(Object object) { // Nashorn creates these mirrors when they pass through certain // boundaries. However, we are only allowed to unwrap them from the same // global context in which they were wrapped. We will try to unwrap them // here, but if that doesn't work we will just create a shallow clone. // The clone won't function like the original, but will be good enough // for our purposes here. object = ScriptObjectMirror.unwrap(object, Context.getGlobal()); if (object instanceof ScriptObjectMirror) { ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) object; ScriptObject scriptObject = NashornNativeUtil.newObject(); for (String key : scriptObjectMirror.getOwnKeys(true)) { Object value = scriptObjectMirror.get(key); scriptObject.put(key, value, false); }//from w w w. j av a2 s . com object = scriptObject; } return object; }
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 ww w. j a v a 2 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 .j a v a2 s . com*/ 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: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); }/*w ww .j ava 2 s. c o m*/ 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:org.bson.jvm.nashorn.ScriptObjectMirrorCodec.java
License:Apache License
@SuppressWarnings("unchecked") public void encode(BsonWriter writer, ScriptObjectMirror scriptObjectMirror, EncoderContext encoderContext) { Object wrapped = ScriptObjectMirror.unwrap(scriptObjectMirror, Context.getGlobal()); if (!(wrapped instanceof ScriptObjectMirror)) { // Attempt to encode the wrapped object Codec<Object> codec = null; try {//from w w w . j a v a 2s . c om codec = (Codec<Object>) codecRegistry.get(wrapped.getClass()); } catch (CodecConfigurationException x) { } if (codec != null) { codec.encode(writer, wrapped, encoderContext); return; } } if (scriptObjectMirror.isArray()) { writer.writeStartArray(); for (int i = 0, length = scriptObjectMirror.size(); i < length; i++) { Object item = scriptObjectMirror.getSlot(i); BsonUtil.writeChild(item, writer, encoderContext, codecRegistry); } writer.writeEndArray(); } else { writer.writeStartDocument(); for (String key : scriptObjectMirror.getOwnKeys(true)) { Object value = scriptObjectMirror.get(key); writer.writeName(key); BsonUtil.writeChild(value, writer, encoderContext, codecRegistry); } writer.writeEndDocument(); } }
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//w w w.j av a2 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//from www . j a va2s . com * @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
/** * Runs launches "fx:bootstrap.js" with the given JavaScript files provided * as arguments./*from www .j av a 2 s .c om*/ * * @param context the nashorn context * @param global the global scope * @param files the list of script files to provide * * @return error code * @throws IOException when any script file read results in I/O error */ private static int runFXScripts(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); } global.addOwnProperty("$GLOBAL", Property.NOT_ENUMERABLE, global); global.addOwnProperty("$SCRIPTS", Property.NOT_ENUMERABLE, files); context.load(global, "fx:bootstrap.js"); } catch (final NashornException e) { context.getErrorManager().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; }