List of usage examples for javax.script ScriptEngine eval
public Object eval(Reader reader) throws ScriptException;
eval(String)
except that the source of the script is provided as a Reader
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); }// w ww .j av a2s.c om // 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: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;// w ww . j a v a2 s .c o m 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:io.lightlink.servlet.JsMethodsDefinitionServlet.java
private Map<String, String> getCustomServices() throws IOException { // list custom services Map<String, String> customServices = new LinkedHashMap<String, String>(); Script customServicesScript = configManager.getScript("#customServices.js", false); if (customServicesScript != null) { ScriptEngine engine = ConfigManager.getScriptEngine(); try {//from w ww. j av a 2s . com Object result = engine.eval(customServicesScript.getContent()); if (result instanceof JSObject) { JSObject jsObject = (JSObject) result; Set<String> keys = jsObject.keySet(); for (String key : keys) { customServices.put(key, "" + jsObject.getMember(key)); } } } catch (ScriptException e) { LogUtils.error(getClass(), e); } } return customServices; }
From source file:com.funambol.rhinounit.maven.plugin.RhinoUnitMojo.java
/** * Runs the test suites in src/test/js// ww w. ja v a 2 s .c om * * */ private void executeTestSuites() throws EngineNotFoundException, ScriptException { final StringBuffer runnerScript = new StringBuffer("var runner = new jsUnitRunner('"); if (getLog().isDebugEnabled()) { getLog().debug("testSourceDirectory: " + testSourceDirectory); } runnerScript.append(testSourceDirectory).append("'); runner.run();"); ScriptEngine engine = getEngine("js"); engine.eval(runnerScript.toString()); }
From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElementTest.java
/** * This is not a test case but more a kind of a sandbox for fiddling around with the script engine *//*from w ww .j av a2 s. c o m*/ @Test public void testEvaluateScriptWithReturn() throws Exception { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer, true); engine.getContext().setWriter(pw); engine.eval(new FileReader("/home/mnxfst/git/stream-analyzer/src/main/resources/spahql.js")); String script = "var result0 = '1';var result1 = '2';"; engine.eval(script); StringBuffer sb = writer.getBuffer(); System.out.println("StringBuffer contains: " + sb + " - " + engine.get("test")); System.out.println(engine.get("content")); for (int i = 0; i < Integer.MAX_VALUE; i++) { String content = (String) engine.get("result" + i); if (StringUtils.isBlank(content)) break; System.out.println(content); } ObjectMapper mapper = new ObjectMapper(); StreamEventMessage message = new StreamEventMessage(); message.setIdentifier("test-id"); message.setOrigin("test-origin"); message.setTimestamp("2014-03-05"); message.setEvent("10"); // message.addCustomAttribute("test-key-1", "3"); // message.addCustomAttribute("test-key-2", "value-1"); // message.addCustomAttribute("test-key-3", "19"); // message.addCustomAttribute("errors", (String)engine.get("test")); String json = mapper.writeValueAsString(message); System.out.println(json); StreamEventMessage msg = mapper.readValue(json, StreamEventMessage.class); System.out.println(message.getCustomAttributes().get("json")); }
From source file:org.eclipse.smarthome.transform.javascript.internal.JavaScriptTransformationService.java
/** * Transforms the input <code>source</code> by Java Script. It expects the * transformation rule to be read from a file which is stored under the * 'configurations/transform' folder. To organize the various * transformations one should use subfolders. * /*from w w w . jav a 2s . com*/ * @param filename * the name of the file which contains the Java script * transformation rule. Transformation service inject input * (source) to 'input' variable. * @param source * the input to transform */ @Override public String transform(String filename, String source) throws TransformationException { Logger logger = LoggerFactory.getLogger(JavaScriptTransformationService.class); if (filename == null || source == null) { throw new TransformationException("the given parameters 'filename' and 'source' must not be null"); } logger.debug("about to transform '{}' by the Java Script '{}'", source, filename); Reader reader; try { String path = ConfigConstants.getConfigFolder() + File.separator + TransformationService.TRANSFORM_FOLDER_NAME + File.separator + filename; reader = new InputStreamReader(new FileInputStream(path)); } catch (FileNotFoundException e) { throw new TransformationException("An error occurred while loading script.", e); } ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); engine.put("input", source); Object result = null; long startTime = System.currentTimeMillis(); try { result = engine.eval(reader); } catch (ScriptException e) { throw new TransformationException("An error occurred while executing script.", e); } finally { IOUtils.closeQuietly(reader); } logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime); return String.valueOf(result); }
From source file:org.eclipse.smarthome.core.transform.internal.service.JavaScriptTransformationService.java
/** * Transforms the input <code>source</code> by Java Script. It expects the * transformation rule to be read from a file which is stored under the * 'configurations/transform' folder. To organize the various * transformations one should use subfolders. * /*from ww w . j av a2 s.c om*/ * @param filename * the name of the file which contains the Java script * transformation rule. Transformation service inject input * (source) to 'input' variable. * @param source * the input to transform */ public String transform(String filename, String source) throws TransformationException { if (filename == null || source == null) { throw new TransformationException("the given parameters 'filename' and 'source' must not be null"); } logger.debug("about to transform '{}' by the Java Script '{}'", source, filename); Reader reader; try { String path = ConfigDispatcher.getConfigFolder() + File.separator + TransformationActivator.TRANSFORM_FOLDER_NAME + File.separator + filename; reader = new InputStreamReader(new FileInputStream(path)); } catch (FileNotFoundException e) { throw new TransformationException("An error occured while loading script.", e); } ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); engine.put("input", source); Object result = null; long startTime = System.currentTimeMillis(); try { result = engine.eval(reader); } catch (ScriptException e) { throw new TransformationException("An error occured while executing script.", e); } finally { IOUtils.closeQuietly(reader); } logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime); return String.valueOf(result); }
From source file:org.springframework.data.hadoop.scripting.Jsr223ScriptEvaluator.java
@Override public Object evaluate(ScriptSource script, Map<String, Object> arguments) { ScriptEngine engine = discoverEngine(script, arguments); Bindings bindings = (!CollectionUtils.isEmpty(arguments) ? new SimpleBindings(arguments) : null); try {//from w ww . java 2 s . c om return (bindings == null ? engine.eval(script.getScriptAsString()) : engine.eval(script.getScriptAsString(), bindings)); } catch (IOException ex) { throw new ScriptCompilationException(script, "Cannot access script", ex); } catch (ScriptException ex) { throw new ScriptCompilationException(script, "Execution failure", ex); } }
From source file:io.github.microcks.web.SoapController.java
private String getDispatchCriteriaFromScriptEval(Operation operation, String body) { ScriptEngineManager sem = new ScriptEngineManager(); try {/*w w w .j a va 2s . com*/ // Evaluating request with script coming from operation dispatcher rules. ScriptEngine se = sem.getEngineByExtension("groovy"); SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body); return (String) se.eval(operation.getDispatcherRules()); } catch (Exception e) { log.error("Error during Script evaluation", e); } return null; }
From source file:org.nuxeo.automation.scripting.internals.AutomationScriptingServiceImpl.java
@Override public void run(String script, CoreSession session) throws ScriptException, OperationException { ScriptEngine engine = engines.get(); engine.setContext(new SimpleScriptContext()); engine.eval(getJSWrapper()); // Initialize Operation Context if (operationContext == null) { operationContext = operationContexts.get(); operationContext.setCoreSession(session); }//from w w w . j a v a 2s. c o m // Injecting Automation Mapper 'automation' AutomationMapper automationMapper = new AutomationMapper(session, operationContext); engine.put(AutomationScriptingConstants.AUTOMATION_MAPPER_KEY, automationMapper); // Inject operation context vars in 'Context' engine.put(AutomationScriptingConstants.AUTOMATION_CTX_KEY, automationMapper.ctx.getVars()); // Session injection engine.put("Session", automationMapper.ctx.getCoreSession()); // User injection PrincipalWrapper principalWrapper = new PrincipalWrapper( (NuxeoPrincipal) automationMapper.ctx.getPrincipal()); engine.put("CurrentUser", principalWrapper); engine.put("currentUser", principalWrapper); // Env Properties injection engine.put("Env", Framework.getProperties()); // DateWrapper injection engine.put("CurrentDate", new DateWrapper()); // Workflow variables injection if (automationMapper.ctx.get(Constants.VAR_WORKFLOW) != null) { engine.put(Constants.VAR_WORKFLOW, automationMapper.ctx.get(Constants.VAR_WORKFLOW)); } if (automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE) != null) { engine.put(Constants.VAR_WORKFLOW_NODE, automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE)); } // Helpers injection ContextService contextService = Framework.getService(ContextService.class); Map<String, ContextHelper> helperFunctions = contextService.getHelperFunctions(); for (String helperFunctionsId : helperFunctions.keySet()) { engine.put(helperFunctionsId, helperFunctions.get(helperFunctionsId)); } engine.eval(script); }