List of usage examples for jdk.nashorn.api.scripting ScriptObjectMirror put
@Override public Object put(final String key, final Object value)
From source file:com.asual.lesscss.compiler.NashornCompiler.java
License:Apache License
public NashornCompiler(LessOptions options, ResourceLoader loader, URL less, URL env, URL engine, URL cssmin, URL sourceMap) throws IOException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine scriptEngine = factory.getEngineByName("nashorn"); try {//w ww . j ava 2 s. c o m scriptEngine.eval(new InputStreamReader(sourceMap.openConnection().getInputStream())); scriptEngine.eval(new InputStreamReader(env.openConnection().getInputStream())); ScriptObjectMirror lessenv = (ScriptObjectMirror) scriptEngine.get("lessenv"); lessenv.put("charset", options.getCharset()); lessenv.put("css", options.isCss()); lessenv.put("lineNumbers", options.getLineNumbers()); lessenv.put("optimization", options.getOptimization()); lessenv.put("sourceMap", options.isSourceMap()); lessenv.put("sourceMapRootpath", options.getSourceMapRootpath()); lessenv.put("sourceMapBasepath", options.getSourceMapBasepath()); lessenv.put("sourceMapURL", options.getSourceMapUrl()); lessenv.put("loader", loader); lessenv.put("paths", options.getPaths()); scriptEngine.eval(new InputStreamReader(less.openConnection().getInputStream())); scriptEngine.eval(new InputStreamReader(cssmin.openConnection().getInputStream())); scriptEngine.eval(new InputStreamReader(engine.openConnection().getInputStream())); compile = (ScriptObjectMirror) scriptEngine.get("compile"); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }
From source file:com.mckoi.webplatform.nashorn.NashornInstanceGlobalFactory.java
License:Open Source License
/** * Initializes the NashornInternal object. * // w ww.ja v a2 s . co m * @param cl the ClassLoader to use, or null for default. */ public void init(final ClassLoader cl) { // Incase we call 'init' more than once, if (PRIV_nashorn_ctx != null) { return; } // Hacky way to return properties from the Nashorn engine, final Object[] inner_data = new Object[5]; // Run initialization in a privileged security context, AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { // We make a VM static NashornScriptEngine that we use to compile // scripts and fork new JavaScript instances. NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); NashornScriptEngine engine; if (cl == null) { engine = (NashornScriptEngine) factory.getScriptEngine(engine_args); } else { engine = (NashornScriptEngine) factory.getScriptEngine(engine_args, cl); } // We add some functions to the global object, ScriptObjectMirror global_object = (ScriptObjectMirror) engine .getBindings(ScriptContext.ENGINE_SCOPE); // A function that performs startup. We execute this to obtain // information about the engine such as the Global and Context object. // It seems the only way to get at this information is from code // running within the engine. global_object.put("engineStartup", new EngineStartupFunction(inner_data)); // Invoke the 'engineStartup' function to get at the priviledged // information. try { engine.invokeFunction("engineStartup", new Object[0]); } catch (ScriptException | NoSuchMethodException ex) { // Oops, throw new RuntimeException(ex); } finally { // Don't leave this function around, just incase, global_object.delete("engineStartup"); } return null; } }); PRIV_nashorn_ctx = (Context) inner_data[0]; // base_nashorn_global = (Global) inner_data[1]; }
From source file:com.tod.utils.logging.FleepAppender.java
License:Open Source License
@Override protected void append(LoggingEvent event) { try {//from w w w . j a va2 s .co m LogLog.debug("Sending 'POST' request to URL: " + url); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/json"); ScriptObjectMirror payload = getJSObject(); if (this.userName != null) { payload.put("user", this.userName); } StringBuffer content = new StringBuffer(); content.append("*"); content.append(event.getLevel().toString()); content.append("* "); content.append(event.getMessage().toString()); String[] stack = event.getThrowableStrRep(); if (stack != null && stack.length > 0) { content.append("\n:::\n"); content.append(String.join("\n", stack)); } payload.put("message", content.toString()); String payloadString = toJSONString(payload); LogLog.debug("Prequest payload: " + payloadString); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payloadString); wr.flush(); wr.close(); LogLog.debug("Response Code: " + con.getResponseCode()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); LogLog.debug("Response: " + response.toString()); } catch (Exception e) { e.printStackTrace(); LogLog.error("Error posting to Fleep", e); } }
From source file:org.jcruncher.less.LessProcessor.java
License:Apache License
public LessProcessor() { try {//from ww w .j a v a 2 s . c om Path basePath = Util.getClasspathBasePath(); //System.out.println("basePath .... " + basePath); Path lessPath = basePath.resolve(LESS_ROOT + "less.js"); Path envPath = basePath.resolve(LESS_ROOT + "env.js"); Path enginePath = basePath.resolve(LESS_ROOT + "engine.js"); ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine nashornEngine = engineManager.getEngineByName("nashorn"); Invocable invocable = (Invocable) nashornEngine; ResourceLoader loader = new FilesystemResourceLoader(); nashornEngine.eval(newBufferedReader(envPath, UTF_8)); ScriptObjectMirror lessenv = (ScriptObjectMirror) nashornEngine.get("lessenv"); lessenv.put("charset", "UTF-8"); lessenv.put("css", false); lessenv.put("loader", loader); nashornEngine.eval(newBufferedReader(lessPath, UTF_8)); nashornEngine.eval(newBufferedReader(enginePath, UTF_8)); compileFunc = (ScriptObjectMirror) nashornEngine.get("compile"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Cannot intialize LessProcessor:\n" + e.getMessage()); } }
From source file:org.siphon.common.js.JsEngineUtil.java
License:Open Source License
public static Object eval(ScriptEngine jsEngine, String srcFile, boolean onlyOnce, boolean preservePathInStack) throws Exception { ScriptObjectMirror importedFiles = (ScriptObjectMirror) jsEngine.get("IMPORTED_FILES"); if (importedFiles.containsKey(srcFile)) { if (onlyOnce) return null; } else {//w w w . j a v a 2s . com importedFiles.put(srcFile, true); } ScriptObjectMirror stk = (ScriptObjectMirror) jsEngine.get("IMPORTS_PATH_STACK"); // NativeArray.pushObject(stk.to(NativeArray.class), srcFile); //stk.callMember("push", srcFile); try { String code = FileUtils.readFileToString(new File(srcFile), "utf-8"); return eval(jsEngine, srcFile, code); } catch (ScriptException | FileNotFoundException e) { throw e; } finally { if (!preservePathInStack) NativeArray.pop(stk.to(NativeArray.class)); } }
From source file:org.siphon.common.js.JsEngineUtil.java
License:Open Source License
public static Object eval(ScriptEngine jsEngine, String srcFile, String aliasPath, String script, boolean onlyOnce, boolean preservePathInStack) throws NoSuchMethodException, ScriptException { ScriptObjectMirror importedFiles = (ScriptObjectMirror) jsEngine.get("IMPORTED_FILES"); if (importedFiles.containsKey(srcFile)) { if (onlyOnce) return null; } else {/*from w w w . j a v a2 s . c o m*/ importedFiles.put(srcFile, true); } ScriptObjectMirror stk = (ScriptObjectMirror) jsEngine.get("IMPORTS_PATH_STACK"); //NativeArray.pushObject((Object)(stk.to(NativeArray.class)), (Object)srcFile); stk.callMember("push", srcFile); try { return eval(jsEngine, aliasPath, script); } catch (ScriptException e) { throw e; } finally { if (!preservePathInStack) NativeArray.pop(stk.to(NativeArray.class)); } }
From source file:org.siphon.common.js.JsTypeUtil.java
License:Open Source License
/** * java js ?? HashMap, List, Date, RegExp, Double, Integer, Long, Float, Boolean byte * @param object//from ww w. j a v a 2 s. com * @return * @throws ScriptException */ public Object javaObjectToJs(Object object) throws ScriptException { if (object == null) return null; if (isStringKeyMap(object)) { ScriptObjectMirror obj = this.newObject(); Map<String, Object> m = (Map<String, Object>) object; for (String key : m.keySet()) { obj.put(key, javaObjectToJs(m.get(key))); } return obj.to(Object.class); } else if (object instanceof List) { ScriptObjectMirror arr = this.newArray(); List objects = (List) object; for (int i = 0; i < objects.size(); i++) { // NativeArray.push(array, objects[i]); arr.callMember("push", javaObjectToJs(objects.get(i))); } return arr.to(Object.class); } else if (object.getClass().isArray()) { ScriptObjectMirror arr = this.newArray(); for (int i = 0; i < Array.getLength(object); i++) { arr.callMember("push", javaObjectToJs(Array.get(object, i))); } return arr.to(Object.class); } else if (object instanceof Date) { return toNativeDate(((Date) object).getTime()); } else if (object instanceof Pattern) { if (this.newRegExp == null) { this.newRegExp = (ScriptObjectMirror) this.engine.get("RegExp"); } return newRegExp.callMember("call", null, ((Pattern) object).pattern()); } else { return object; } }
From source file:org.siphon.d2js.D2jsFormatter.java
License:Open Source License
@Override public String formatException(Object exception, ScriptEngine engine) throws Exception { if (exception instanceof ScriptObjectMirror) { return formatException(JsTypeUtil.getSealed((ScriptObjectMirror) exception), engine); } else if (exception instanceof ScriptObject) { //NativeError, NativeTypeError, NativeEvalError, ... // JSON.stringify Error ??? hack instMessage // if(((ScriptObject) exception).getOwnKeys(false).length == 0){ // Object instMessage = ((ScriptObject) exception).get("message"); // instMessage // if(instMessage != null){ // exception = instMessage; // } // } } else if (exception instanceof SqlExecutorException) { SqlExecutorException sqlExecutorException = (SqlExecutorException) exception; if (sqlExecutorException.getCause() instanceof SQLException) { exception = sqlExecutorException.getCause().getMessage(); } else {//from w w w .j ava 2 s . c om exception = sqlExecutorException.getMessage(); } } else if (exception instanceof Throwable) { if (((Throwable) exception).getCause() instanceof SqlExecutorException) { return formatException(((Throwable) exception).getCause(), engine); } exception = ((Throwable) exception).getMessage(); } else { exception = exception.toString(); } ScriptObjectMirror result = new JsTypeUtil(engine).newObject(); result.put("error", exception); return new JSON(engine).stringify(result); }
From source file:org.siphon.d2js.D2jsFormatter.java
License:Open Source License
@Override public String formatException(String exception, ScriptEngine engine) throws Exception { JsTypeUtil jsTypeUtil = new JsTypeUtil(engine); ScriptObjectMirror result = jsTypeUtil.newObject(); result.put("error", exception); return new JSON(engine).stringify(result); }
From source file:org.siphon.d2js.D2jsRunner.java
License:Open Source License
protected String getParams(JsspRequest request) throws Exception { String s = request.getParameter("params"); if (s != null) { return s; }// ww w . j a v a 2s .c om ScriptObjectMirror params = jsTypeUtil.newObject(); Map<String, String[]> parameterMap = request.getParameterMap(); for (String p : parameterMap.keySet()) { params.put(p, request.get(p)); } return com.alibaba.fastjson.JSON.toJSONString(params); }