List of usage examples for javax.script ScriptEngine get
public Object get(String key);
From source file:com.netsteadfast.greenstep.util.ScriptExpressionUtils.java
private static void executeRenjin(String scriptExpression, Map<String, Object> results, Map<String, Object> parameters) throws Exception { ScriptEngine engine = buildRenjinScriptEngine(); if (parameters != null) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { engine.put(entry.getKey(), entry.getValue()); }//from w w w . j a v a 2 s . c om } engine.eval(scriptExpression); if (results != null) { for (Map.Entry<String, Object> entry : results.entrySet()) { Object res = engine.get(entry.getKey()); if (res instanceof AbstractAtomicVector) { if (((AbstractAtomicVector) res).length() > 0) { entry.setValue(((AbstractAtomicVector) res).getElementAsObject(0)); } } else { entry.setValue(res); } } } }
From source file:org.quackbot.hooks.loaders.JSHookLoaderTest.java
@Test(dataProvider = "commandOptionalArrayDataProvider") public void commandOptionalArrayTest(String[] extraArgs) throws Exception { log.trace("--- Begin commandOptionalArrayTest with args " + Arrays.toString(extraArgs) + " ---"); JSHookLoader.JSCommandWrapper hook = (JSHookLoader.JSCommandWrapper) loader .load("JSPluginTest/Command_OptionalArray.js"); //Make sure arguments are setup correctly assertEquals(hook.getRequiredParams(), 2, "Required argument count is wrong"); assertEquals(hook.getOptionalParams(), -1, "Optional argument count is wrong"); //Test sending a command with several args MessageEvent messageEvent = new MessageEvent(bot, null, null, "Some message"); CommandEvent commandEvent = new CommandEvent(null, messageEvent, null, null, "?command someArg1 someArg2 " + StringUtils.join(extraArgs, ", "), null, (String[]) ArrayUtils.addAll(new String[] { "someArg1", "someArg2" }, extraArgs)); String returned = hook.onCommand(commandEvent); ScriptEngine engine = hook.jsEngine; assertEquals(returned, "Success", "Returned value doesn't match given"); assertEquals(engine.get("event"), commandEvent, "Event doesn't match given"); assertEquals(engine.get("arg1"), "someArg1", "First argument doesn't match given"); assertEquals(engine.get("arg2"), "someArg2", "Second argument doesn't match given"); //In order to verify the arg array, need to convert back to a Java array Object[] argArray = (Object[]) ((Invocable) engine).invokeMethod(engine.get("QuackUtils"), "toJavaArray", Object.class, engine.get("argArray3")); for (int i = 0; i < extraArgs.length; i++) { log.trace("Arg array: " + Arrays.toString(argArray)); Object commandArg = argArray[i]; log.trace("Got command arg successfully"); Object extraArg = extraArgs[i]; assertEquals(commandArg, extraArg, "Extra arg #" + i + " doesn't match given"); }/*from w w w.j av a 2 s. c o m*/ }
From source file:reconf.server.services.JavaScriptEngine.java
public Object eval(String js, Map<String, Object> params, String resultVariableName) { try {// w w w .j a v a 2 s . c om ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); for (Entry<String, Object> each : params.entrySet()) { engine.put(each.getKey(), each.getValue()); } engine.eval(js); return engine.get(resultVariableName); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java
private String extractKey(String jk) throws ScriptException { final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine scriptEngine = scriptEngineManager.getEngineByMimeType("text/javascript"); scriptEngine.eval(jk + "\nvar result = f();"); return scriptEngine.get("result").toString(); }
From source file:org.siphon.db2js.DbjsRunner.java
public void completeTask(ScriptEngine engine, Exception exception) throws Exception { Task task = (Task) engine.get("jscurrtask"); if (task != null) { ScriptObjectMirror cb = null;//from www. ja v a 2s . c o m if (exception == null) { cb = (ScriptObjectMirror) task.end(); } else { cb = (ScriptObjectMirror) task.end(exception, engine); } if (cb != null && cb.containsKey("callback")) { ((Invocable) engine).invokeMethod(cb, "callback", cb); } engine.put("jscurrtask", null); } }
From source file:it.delli.mwebc.command.impl.EventCommand.java
public void execute(Page page, JsonObject data) { String eventName = data.get("event").getAsString(); String eventType = data.get("eventType").getAsString(); String method = data.get("forward").getAsString(); Widget widget = null;/* www . j ava 2 s . c om*/ EventListener eventListener = null; if (data.get("id") != null) { widget = page.getWidget(data.get("id").getAsString()); eventListener = widget.getEventListener(eventName); } else { eventListener = page.getEventListener(); } Class eventTypeClass = page.getApplication().getEventClass(eventType); Event event = null; try { event = (Event) eventTypeClass.getConstructor(String.class, Widget.class, JsonObject.class) .newInstance(eventName, widget, data.get("data").getAsJsonObject()); } catch (Exception e) { log.error("Exception in creating event instance for event type " + eventType); } ; event.setPage(page); // bind widgets ReflectionUtils.bindWidgets(eventListener, page); // Method forwardMethod = null; if (eventListener instanceof PageEventListener && page.getWidget(method) != null) { try { it.delli.mwebc.widget.Method widgetMethod = (it.delli.mwebc.widget.Method) page.getWidget(method); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("groovy"); engine.put("eventListener", null); engine.eval(widgetMethod.getScript()); eventListener = (EventListener) engine.get("eventListener"); forwardMethod = eventListener.getClass().getMethod(method, Event.class); forwardMethod.setAccessible(true); } catch (Exception e) { log.error("Exception in getting method to execute", e); } } else { try { forwardMethod = eventListener.getClass().getMethod(method, Event.class); forwardMethod.setAccessible(true); } catch (Exception e) { log.error("Exception in getting method to execute", e); } } if (forwardMethod != null) { if (event.getWidget() != null) { log.info("Executing forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName() + " on widget " + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")"); } else { log.info("Executing forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName()); } try { forwardMethod.invoke(eventListener, event); } catch (Exception e) { if (event.getWidget() != null) { log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName() + " on widget " + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")", e); } else { log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName(), e); } log.error("Exception in forward method execution", e); } } else { log.info("Forward method does not exist in event listener " + eventListener.getClass().getName() + " for event " + event.getName()); log.info("Notifying end of failed execution for event " + event.getName()); } }
From source file:edu.anu.spice.SpiceScorer.java
public void scoreBatch(SpiceArguments args) throws IOException, ScriptException { Stopwatch timer = Stopwatch.createStarted(); SpiceParser parser = new SpiceParser(args.cache, args.numThreads, args.synsets); // Build filters for tuple categories Map<String, TupleFilter> filters = new HashMap<String, TupleFilter>(); if (args.tupleSubsets) { filters.put("Object", TupleFilter.objectFilter); filters.put("Attribute", TupleFilter.attributeFilter); filters.put("Relation", TupleFilter.relationFilter); filters.put("Cardinality", TupleFilter.cardinalityFilter); filters.put("Color", TupleFilter.colorFilter); filters.put("Size", TupleFilter.sizeFilter); }/*from ww w . ja va2 s .co m*/ // Parse test and refs from input file ArrayList<Object> image_ids = new ArrayList<Object>(); ArrayList<String> testCaptions = new ArrayList<String>(); ArrayList<String> refCaptions = new ArrayList<String>(); ArrayList<Integer> refChunks = new ArrayList<Integer>(); JSONParser json = new JSONParser(); JSONArray input; try { input = (JSONArray) json.parse(new FileReader(args.inputPath)); for (Object o : input) { JSONObject item = (JSONObject) o; image_ids.add(item.get("image_id")); testCaptions.add((String) item.get("test")); JSONArray refs = (JSONArray) item.get("refs"); refChunks.add(refs.size()); for (Object ref : refs) { refCaptions.add((String) ref); } } } catch (ParseException e) { System.err.println("Could not read input: " + args.inputPath); System.err.println(e.toString()); e.printStackTrace(); } System.err.println("Parsing reference captions"); List<SceneGraph> refSgs = parser.parseCaptions(refCaptions, refChunks); System.err.println("Parsing test captions"); List<SceneGraph> testSgs = parser.parseCaptions(testCaptions); this.stats = new SpiceStats(filters, args.detailed); for (int i = 0; i < testSgs.size(); ++i) { this.stats.score(image_ids.get(i), testSgs.get(i), refSgs.get(i), args.synsets); } if (!args.silent) { System.out.println(this.stats.toString()); } if (args.outputPath != null) { BufferedWriter outputWriter = new BufferedWriter(new FileWriter(args.outputPath)); // Pretty print output using javascript String jsonStringNoWhitespace = this.stats.toJSONString(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine scriptEngine = manager.getEngineByName("JavaScript"); scriptEngine.put("jsonString", jsonStringNoWhitespace); scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)"); String prettyPrintedJson = (String) scriptEngine.get("result"); outputWriter.write(prettyPrintedJson); outputWriter.close(); } System.out.println("SPICE evaluation took: " + timer.stop()); }
From source file:org.geoserver.script.py.PyAppHook.java
@Override public void run(Request request, Response response, ScriptEngine engine) throws ScriptException, IOException { Object obj = engine.get("app"); if (obj == null) { throw new RuntimeException("No 'app' function defined"); }// w w w .ja v a2 s. c om if (!(obj instanceof PyObject)) { throw new RuntimeException("'app not callable, found a " + obj.toString()); } PyObject app = (PyObject) obj; WSGIResponse wr = new WSGIResponse(); RESPONSE.set(wr); try { Object ret = app.__call__(new PyObject[] { createEnviron(request), createStartResponse() }); if (ret != null) { String contentType = wr.headers.get("content-type"); if (contentType == null) { contentType = "text/plain"; } MediaType mediaType = new MediaType(contentType); if (ret instanceof PyString) { response.setEntity(ret.toString(), mediaType); } else if (ret instanceof PyList) { final PyList list = (PyList) ret; response.setEntity(new OutputRepresentation(mediaType) { @Override public void write(OutputStream outputStream) throws IOException { for (Iterator i = list.iterator(); i.hasNext();) { outputStream.write(i.next().toString().getBytes()); if (i.hasNext()) { outputStream.write('\n'); } } } }); } else if (ret instanceof PyIterator) { final PyIterator iter = (PyIterator) ret; response.setEntity(new OutputRepresentation(mediaType) { @Override public void write(OutputStream outputStream) throws IOException { for (Iterator i = iter.iterator(); i.hasNext();) { outputStream.write(i.next().toString().getBytes()); outputStream.write('\n'); } } }); } else if (ret instanceof PyObjectDerived) { final PyObjectDerived iter = (PyObjectDerived) ret; response.setEntity(new OutputRepresentation(mediaType) { @Override public void write(OutputStream outputStream) throws IOException { PyObject next = null; while ((next = iter.__iternext__()) != null) { outputStream.write(next.toString().getBytes()); outputStream.write('\n'); } } }); } else { LOGGER.warning( "Unsure how to handle " + ret + ". Resorting to outputing string " + "representation."); response.setEntity(ret.toString(), mediaType); } } } finally { RESPONSE.remove(); } }
From source file:com.asual.lesscss.compiler.NashornCompiler.java
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 {/*from ww w . j a va2 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.servioticy.dispatcher.SOProcessor010.java
public boolean checkFilter(JsonPathReplacer filterField, Map<String, String> inputJsons) throws ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); if (filterField == null) { return true; }/*from w w w . j a va 2 s . c om*/ String filterCode = filterField.replace(inputJsons); engine.eval("var result = Boolean(" + filterCode + ")"); return (Boolean) engine.get("result"); }