List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. 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 w ww.j a va 2 s.c o 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.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$ }//from w w w. ja v a 2 s .co 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; }
From source file:net.mindengine.galen.suite.actions.GalenPageActionRunJavascript.java
@Override public List<ValidationError> execute(Browser browser, GalenPageTest pageTest, ValidationListener validationListener) throws Exception { File file = GalenUtils.findFile(javascriptPath); Reader scriptFileReader = new FileReader(file); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); ScriptContext context = engine.getContext(); context.setAttribute("name", "JavaScript", ScriptContext.ENGINE_SCOPE); engine.put("global", new ScriptExecutor(engine, file.getParent())); engine.put("browser", browser); provideWrappedWebDriver(engine, browser); importAllMajorClasses(engine);/*from w w w. j av a 2s .c om*/ engine.eval("var arg = " + jsonArguments); engine.eval(scriptFileReader); return NO_ERRORS; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testGroovy() throws ScriptException { String engineName = "groovy"; ScriptEngineManager mgr = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = mgr.getEngineByName(engineName); assertNotNull("Can't find engine '" + engineName + "'", engine); ScriptEngineFactory sef = engine.getFactory(); System.out.println("FACTORY for " + engineName + ": " + "'" + sef.getEngineName() + "' " + "'" + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' "); // evaluate code from String engine.eval("println \"hello, groovy\""); }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testGroovyFileAndParam() throws ScriptException, IOException { String engineName = "groovy"; ScriptEngineManager mgr = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = mgr.getEngineByName(engineName); assertNotNull("Can't find engine '" + engineName + "'", engine); File script = new ClassPathResource("test-data/test.groovy").getFile(); assertNotNull("Can't find test script", script); engine.put("gbtest", "testok"); // evaluate code from File engine.eval(new FileReader(script)); }
From source file:org.apache.ranger.plugin.conditionevaluator.RangerScriptConditionEvaluator.java
@Override public void init() { if (LOG.isDebugEnabled()) { LOG.debug("==> RangerScriptConditionEvaluator.init(" + condition + ")"); }// ww w . j a va 2 s .c om super.init(); String engineName = "JavaScript"; Map<String, String> evalOptions = conditionDef.getEvaluatorOptions(); if (MapUtils.isNotEmpty(evalOptions)) { engineName = evalOptions.get("engineName"); } if (StringUtils.isBlank(engineName)) { engineName = "JavaScript"; } if (LOG.isDebugEnabled()) { LOG.debug("RangerScriptConditionEvaluator.init() - engineName=" + engineName); } try { ScriptEngineManager manager = new ScriptEngineManager(); scriptEngine = manager.getEngineByName(engineName); } catch (Exception exp) { LOG.error("RangerScriptConditionEvaluator.init() failed with exception=" + exp); } if (LOG.isDebugEnabled()) { LOG.debug("<== RangerScriptConditionEvaluator.init(" + condition + ")"); } }
From source file:org.sonar.fortify.crawler.Main.java
private void executeJSCode(String pageSrc) throws ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.put("d", this); engine.eval(pageSrc);//from w w w .j a v a2s . c o m }
From source file:com.qwazr.scripts.ScriptManager.java
private ScriptManager(ExecutorService executorService, File rootDirectory) throws IOException, URISyntaxException { // Load Nashorn ScriptEngineManager manager = new ScriptEngineManager(); scriptEngine = manager.getEngineByName("nashorn"); runsMap = new HashMap<String, RunThreadAbstract>(); this.executorService = executorService; }
From source file:com.viddu.handlebars.HandlebarsNashorn.java
HandlebarsNashorn(Reader handlebarsLib) throws HandlebarsException { ScriptEngineManager engineManager = new ScriptEngineManager(); this.engine = engineManager.getEngineByName("nashorn"); try {/* www. java2 s. c o m*/ engine.eval(handlebarsLib); handlebars = engine.eval("Handlebars"); JSON = engine.eval("JSON"); engine.eval("var ScriptUtils = Java.type('jdk.nashorn.api.scripting.ScriptUtils')\n" + "var wrapper = function(name, biFunctionInstance){\n" + " Handlebars.registerHelper(name, function(context, options){\n" + " var wrappedContext = ScriptUtils.wrap(context);\n" + " var wrappedOptions = ScriptUtils.wrap(options);\n" + " return biFunctionInstance.apply(wrappedContext, wrappedOptions); \n" + " }); \n" + "}"); } catch (ScriptException e) { logger.debug("Error in script:{}", e); throw new HandlebarsException(e); } this.objectMapper = new ObjectMapper(); this.objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE); this.mapper = new ObjectMapper(); }
From source file:org.craftercms.engine.scripting.impl.Jsr233CompiledScriptFactory.java
@PostConstruct public void init() { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = (Compilable) scriptEngineManager.getEngineByName(scriptEngineName); }