List of usage examples for javax.script ScriptEngine put
public void put(String key, Object value);
From source file:com.seajas.search.contender.scripting.FeedScriptsTestBase.java
/** * Evaluates the script./*from w ww . j a v a2 s . c om*/ */ protected SyndFeed run(final String feedUri, final String scriptFile) throws Exception { final ScriptEngine engine = engineManager.getEngineByMimeType("text/javascript"); injectionService = new MockInjectionService(); subject = new FeedScriptEvaluation(new WebResolverSettings()); subject.setScriptResolver(new ScriptCacheResolver<FeedScript>() { @Override public FeedScript resolve(final Bindings bindings) throws ScriptException { try { for (Map.Entry<String, Object> entry : bindings.entrySet()) engine.put(entry.getKey(), entry.getValue()); engine.eval(readFileToString(new File("src/main/scripts/feed/" + scriptFile), "UTF-8")); return ((Invocable) engine).getInterface(FeedScript.class); } catch (IOException e) { throw new IllegalArgumentException("Invalid script", e); } } }); if (scriptFile.endsWith(".js")) subject.setEngine(engine); else throw new IllegalArgumentException("Unknown script file extension."); subject.setFeedContent(samples.values().iterator().next()); subject.setWebPages(new WebPages()); subject.setWebResolver(new WebResolver() { @Override public String retrieveText(URI resource) { return samples.get(resource.toString()); } }); subject.setFeedURI(new URI(feedUri)); subject.setCacheResolver(new FeedScriptCacheResolver() { @Override public boolean isCached(String resource) { return false; } }); subject.setInjectionService(injectionService); subject.init(); subject.run(); SyndFeed feed = subject.getFeed(); assertNotNull("feed", feed); // The validated feed must be serializable: SyndFeed result = (SyndFeed) feed.clone(); WebFeeds.validate(result, new URI(feedUri)); new SyndFeedOutput().outputString(result, true); return feed; }
From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java
@Test public void testNashornWithCompile() throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE); assertNotNull(engine);/* w w w . ja v a 2s . c o m*/ Compilable compiler = (Compilable) engine; assertNotNull(compiler); InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js"); assertNotNull(stream); String js = IOUtils.toString(stream); CompiledScript compiled = compiler.compile(new StringReader(js)); engine.put("mapper", new Mapper()); compiled.eval(engine.getContext()); assertEquals("1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]" + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2" + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}" + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString()); }
From source file:mrf.Graficar.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); ArrayList<Integer> Datosx = new ArrayList<Integer>(); ArrayList<Double> Datosy = new ArrayList<Double>(); int in = Integer.parseInt(jTextField2.getText()); int sup = Integer.parseInt(jTextField3.getText()); try {/* w w w .ja va2s .c o m*/ XYSeries series = new XYSeries(""); int inferior = in, superior = sup; while (inferior <= superior) { Datosx.add(inferior); engine.put("X", inferior); String a = jTextField1.getText(); Object operation = engine.eval(a); Datosy.add(Double.parseDouble("" + operation)); jTextArea1.append("Parejas ordenadas " + inferior + ":" + operation + "\n"); series.add(inferior, Double.parseDouble("" + operation)); inferior++; } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart("Grafica del polinomio ingresado", // Ttulo "Eje x", // Etiqueta Coordenada X "Eje y", // Etiqueta Coordenada Y dataset, // Datos PlotOrientation.VERTICAL, true, // Muestra la leyenda de los productos (Producto A) false, false); // Mostramos la grafica en pantalla ChartFrame frame = new ChartFrame("GRAFICA POLINOMIO", chart); frame.pack(); frame.setVisible(true); } catch (ScriptException e) { e.printStackTrace(); } }
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());/*from w w w . ja va2 s . c om*/ // Initialize Operation Context if (operationContext == null) { operationContext = operationContexts.get(); operationContext.setCoreSession(session); } // 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); }
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 w w w . j av a2 s .c om*/ 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:com.funambol.rhinounit.maven.plugin.RhinoUnitMojo.java
/** * Returns the ScripEngine for the given script extension. Engines are * stored and reused so that only one engine per extension will be returned. * If the engine for a given extension does not exist, EngineNotFoundException * is thrown.//from www .j av a2 s.c o m * * @return the engine * * @throws EngineNotFoundException if no engine is found for the given extension */ public ScriptEngine getEngine(String extension) throws EngineNotFoundException { // // Let's initialize engines if necessary... // if (engines == null) { engines = new HashMap<String, ScriptEngine>(); } ScriptEngine engine = engines.get(extension); if (engine == null) { ScriptEngineManager engineManager = new ScriptEngineManager(); if ((engine = engineManager.getEngineByExtension(extension)) == null) { throw new EngineNotFoundException(extension); } if (passProjectAsProperty) { if (nameOfProjectProperty == null) { nameOfProjectProperty = DEFAULT_NAME_OF_PROJECT_PROPERTY; } engine.put(nameOfProjectProperty, project); } engines.put(extension, engine); } return engine; }
From source file:com.seajas.search.contender.service.modifier.ModifierScriptProcessor.java
/** * Evaluate the given script./* www.j a va2 s.co m*/ * * @param settings * @param script * @param input * @param uri * @return String * @throws ScriptException */ private String evaluateScript(final WebResolverSettings settings, final ModifierScript script, String input, URI uri) throws ScriptException { final ScriptCacheEntry entry = scriptCache.acquireScript(script); try { final ScriptEngine engine = entry != null ? entry.getScript().getEngine() : engineManager.getEngineByName(script.getScriptLanguage().toLowerCase()); FeedScriptEvaluation evaluation = new FeedScriptEvaluation(settings); evaluation.setScriptResolver(new ScriptCacheResolver<FeedScript>() { @Override public FeedScript resolve(final Bindings bindings) throws ScriptException { for (Map.Entry<String, Object> binding : bindings.entrySet()) engine.put(binding.getKey(), binding.getValue()); if (entry != null) { if (logger.isTraceEnabled()) logger.trace("Executing compiled script with ID " + script.getId()); entry.getScript().eval(); } else { if (logger.isTraceEnabled()) logger.trace(String.format("Executing non-compiled script with ID %d and content '%s'", script.getId(), script.getScriptContent())); engine.eval(script.getScriptContent()); } return ((Invocable) engine).getInterface(FeedScript.class); } }); evaluation.setFeedURI(uri); evaluation.setFeedContent(input); evaluation.setEngine(engine); evaluation.setCacheResolver(new FeedScriptCacheResolver() { @Override public boolean isCached(final String resource) { logger.info("Cache requested URI: " + resource); String cacheKey = cacheService.createCompositeKey(resource, settings.getResultParameters()); return cacheService.isCached(cacheKey); } }); evaluation.setWebPages(new WebPages()); DefaultWebResolver resolver = new DefaultWebResolver(); resolver.setSettings(settings); resolver.setContenderService(contenderService); evaluation.setWebResolver(resolver); evaluation.init(); evaluation.run(); SyndFeed feed = evaluation.getFeed(); if (feed == null) throw new ScriptException("No result available"); try { WebFeeds.validate(feed, uri); SyndFeedOutput serializer = new SyndFeedOutput(); return serializer.outputString(feed, true); } catch (FeedException e) { throw new ScriptException("Can't serialize feed result: " + e); } } finally { scriptCache.releaseScript(script, entry); } }
From source file:org.openadaptor.auxil.processor.script.ScriptProcessor.java
/** * This will attempt to bind named objects into the ScriptEngine. * <br>/*from ww w . j ava 2s .c o m*/ * The key of each Map.Entry will be used as the bound name within * the engine. * The value object will be bound to that name withing the engine. * @param engine ScriptEngine to apply bindings in. * @param bindings Map of name to Object pairings */ private void applyBindings(ScriptEngine engine, Map bindings) { if (bindings != null) { log.info("Applying additionalBindings"); Iterator it = bindings.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); Object value = bindings.get(key); engine.put(key.toString(), value); if (log.isDebugEnabled()) { log.debug("Binding " + key.toString() + " -> " + value); } } } }
From source file:org.samjoey.gui.GraphicalViewer.java
private void selectedPGN(File file) { String fileLoc = file.getAbsolutePath(); //fileLoc = "File:" + fileLoc.substring(2); if (fileLoc.substring(fileLoc.length() - 3).equals("pgn")) { for (int i = 0; i < fileLoc.length(); i++) { if (fileLoc.substring(i, i + 1).equals("/")) { fileLoc = fileLoc.substring(0, i) + "\\" + fileLoc.substring(i + 1); }//from w ww .j av a 2 s . c o m } try { // Below: Talk to JavaScript ScriptEngineManager factory = new ScriptEngineManager(); // create JavaScript engine final ScriptEngine engine = factory.getEngineByName("JavaScript"); // evaluate JavaScript code from given file - specified by first argument engine.put("engine", engine); ClassLoader cl = GraphicalViewer.class.getClassLoader(); // Talk to GameLooper_1 URL url = cl.getResource("\\org\\samjoey\\gameLooper\\GameLooper_1.js"); String loopLoc = url.toString().substring(5); for (int i = 0; i < loopLoc.length() - 3; i++) { if (loopLoc.substring(i, i + 3).equals("%5c")) { loopLoc = loopLoc.substring(0, i) + "/" + loopLoc.substring(i + 3); } } engine.put("loopLoc", loopLoc); // Talk to calcDefs_1 url = cl.getResource("\\org\\samjoey\\calculator\\calcDefs_1.js"); String defsLoc = url.toString().substring(5); for (int i = 0; i < defsLoc.length() - 3; i++) { if (defsLoc.substring(i, i + 3).equals("%5c")) { defsLoc = defsLoc.substring(0, i) + "/" + defsLoc.substring(i + 3); } } engine.put("defsLoc", defsLoc); // Talk to Calculator url = cl.getResource("\\org\\samjoey\\calculator\\Calculator.js"); String calcLoc = url.toString().substring(5); for (int i = 0; i < calcLoc.length() - 3; i++) { if (calcLoc.substring(i, i + 3).equals("%5c")) { calcLoc = calcLoc.substring(0, i) + "/" + calcLoc.substring(i + 3); } } engine.put("calcLoc", calcLoc); String args[] = { "-g:false", fileLoc }; engine.put("arguments", args); // Create a Thread to update the parser's progress bar parserProgress.setStringPainted(true); running = false; running = true; Thread thread = new Thread() { @Override public void run() { long last = 0l; boolean print = true; double p = .01; while (engine.get("progress") == null || engine.get("size") == null || Integer.parseInt((String) engine.get("progress")) != Integer .parseInt((String) engine.get("size"))) { //if (Parser.numGames > 0 && Parser.progress == Parser.numGames) { try { parserProgress.setValue(Integer.parseInt((String) engine.get("progress"))); parserProgress.setMaximum(Integer.parseInt((String) engine.get("size"))); if (last == 0l) { last = System.nanoTime(); } if ((double) parserProgress.getValue() / (double) parserProgress.getMaximum() > p && print) { //System.out.println(p + ": " + (System.nanoTime() - last)); //print = false; p += .01; } } catch (Exception e) { } //} else { // parserProgress.setMaximum(Parser.numGames - 1); // parserProgress.setMinimum(0); // parserProgress.setValue(Parser.progress); //} } // finally parserProgress.setValue(parserProgress.getMaximum()); } }; thread.start(); // I have no clue what's here!?? engine.eval(new java.io.FileReader( GraphicalViewer.class.getClassLoader().getResource("driver_1.js").toString().substring(5))); while (games == null || games.get((int) (Math.random() * games.size())).getVarData().size() < 20) { games = (LinkedList<Game>) engine.get("gameList"); } } catch (ScriptException | FileNotFoundException ex) { Logger.getLogger(GraphicalViewer.class.getName()).log(Level.SEVERE, null, ex); } } else if (fileLoc.substring(fileLoc.length() - 4).equals("jsca")) { JSCAParser jsca = new JSCAParser(fileLoc); games = (LinkedList<Game>) jsca.getGamesList(); } Set<String> keys = games.get(0).getVarData().keySet(); for (String key : keys) { Variable_Chooser.addItem(key); } graphs = GraphUtility.getGraphs(games); setViewer(0, 0); }
From source file:org.pentaho.platform.plugin.condition.scriptable.ScriptableCondition.java
public boolean shouldExecute(final Map currentInputs, final Log logger) throws Exception { boolean shouldExecute = this.getDefaultResult(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName(this.getScriptLanguage()); if (engine == null) { throw new IllegalArgumentException(Messages.getInstance().getErrorString( "ScriptableCondition.ERROR_0001_ENGINE_NOT_AVAILABLE", this.getScriptLanguage())); //$NON-NLS-1$ }//w ww . j a v a 2s .c o m Object inputValue; IActionParameter inputParameter; String inputName = null; Iterator inputs = currentInputs.entrySet().iterator(); Map.Entry mapEntry; while (inputs.hasNext()) { mapEntry = (Map.Entry) inputs.next(); inputName = (String) mapEntry.getKey(); if (this.getIgnoreInputNamesWithMinus() && inputName.indexOf('-') >= 0) { logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_IGNORED_INPUT", inputName)); //$NON-NLS-1$ continue; } inputParameter = (IActionParameter) mapEntry.getValue(); inputValue = inputParameter.getValue(); engine.put(inputName, inputValue); // What happens to resultset objects I wonder... } engine.put("out", System.out); engine.put("rule", this); Object resultObject = engine.eval(this.getScript()); if (resultObject instanceof Boolean) { return ((Boolean) resultObject).booleanValue(); } else if (resultObject instanceof String) { return ("true".equalsIgnoreCase(resultObject.toString())) || ("yes".equalsIgnoreCase(resultObject.toString())); //$NON-NLS-1$ //$NON-NLS-2$ } else if (resultObject instanceof Number) { return ((Number) resultObject).intValue() > 0; } else if (resultObject instanceof IPentahoResultSet) { return ((IPentahoResultSet) resultObject).getRowCount() > 0; } logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_DEFAULT_RESULT_RETURNED")); //$NON-NLS-1$ return shouldExecute; }