List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. From source file:org.wso2.carbon.event.template.manager.core.internal.util.TemplateManagerHelper.java
/** * Create a JavaScript engine packed with given scripts. If two scripts have methods with same name, * later method will override the previous method. * * @param domain//from ww w.jav a 2s . co m * @return JavaScript engine * @throws TemplateDeploymentException if there are any errors in JavaScript evaluation */ public static ScriptEngine createJavaScriptEngine(Domain domain) throws TemplateDeploymentException { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager .getEngineByName(TemplateManagerConstants.JAVASCRIPT_ENGINE_NAME); if (scriptEngine == null) { // Exception will be thrown later, only if function calls are used in the template log.warn("JavaScript engine is not available. Function calls in the templates cannot be evaluated"); } else { if (domain != null && domain.getScripts() != null && domain.getScripts().getScript() != null) { Path scriptDirectory = Paths.get(TemplateManagerConstants.TEMPLATE_SCRIPT_PATH); if (Files.exists(scriptDirectory, LinkOption.NOFOLLOW_LINKS) && Files.isDirectory(scriptDirectory)) { for (Script script : domain.getScripts().getScript()) { String src = script.getSrc(); String content = script.getContent(); if (src != null) { // Evaluate JavaScript file Path scriptFile = scriptDirectory.resolve(src).normalize(); if (Files.exists(scriptFile, LinkOption.NOFOLLOW_LINKS) && Files.isReadable(scriptFile)) { if (!scriptFile.startsWith(scriptDirectory)) { // The script file is not in the permitted directory throw new TemplateDeploymentException("Script file " + scriptFile.toAbsolutePath() + " is not in the permitted directory " + scriptDirectory.toAbsolutePath()); } try { scriptEngine .eval(Files.newBufferedReader(scriptFile, Charset.defaultCharset())); } catch (ScriptException e) { throw new TemplateDeploymentException("Error in JavaScript " + scriptFile.toAbsolutePath() + ": " + e.getMessage(), e); } catch (IOException e) { throw new TemplateDeploymentException( "Error in reading JavaScript file: " + scriptFile.toAbsolutePath()); } } else { throw new TemplateDeploymentException("JavaScript file not exist at: " + scriptFile.toAbsolutePath() + " or not readable."); } } if (content != null) { // Evaluate JavaScript content try { scriptEngine.eval(content); } catch (ScriptException e) { throw new TemplateDeploymentException( "JavaScript declared in " + domain.getName() + " has error", e); } } } } else { log.warn("Script directory not found at: " + scriptDirectory.toAbsolutePath()); } } } return scriptEngine; }
From source file:reconf.server.services.JavaScriptEngine.java
public Object eval(String js, Map<String, Object> params, String resultVariableName) { try {//ww w . java2s . com 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:temp.groovy.java
@Test public void foo() { JexlEngine eng = new JexlEngine(); eng.setLenient(false);// ww w . ja va 2s. co m eng.setSilent(false); Expression expr = eng.createExpression("a == '9' and a =~ ['7','9']"); System.out.println(expr.dump()); JexlContext ctx = new MapContext(); ctx.set("a", "9"); Boolean result = (Boolean) expr.evaluate(ctx); try { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("jython"); engine.put("first", 9); result = (Boolean) engine.eval("first not in [7,9]"); result = (Boolean) engine.eval("first in ['7','9']"); assertEquals(true, result); //This next example illustrates calling an invokable function: String fact = "def factorial(n) { n == 1 ? 1 : n * factorial(n - 1) }"; engine.eval(fact); Invocable inv = (Invocable) engine; Object[] params = { 5 }; Object oresult = inv.invokeFunction("factorial", params); assertEquals(120, oresult); } catch (ScriptException | NoSuchMethodException ex) { Logger.getLogger(groovy.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.tamilunicodeconverter.converter.BaminiConverter.java
public String getUnicodeTextUsingJavaScript(String text) { String unicodeText = ""; try {/*from w w w . j a v a2 s . c o m*/ ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(getScriptContent()); Invocable invokable = (Invocable) engine; unicodeText = (String) invokable.invokeFunction("convert", new String[] { text }); } catch (Exception ex) { throw new UnhandledException("Error occured while converting bamini text to unicode", ex); } return unicodeText; }
From source file:mondrian.util.UtilCompatibleJdk16.java
public <T> T compileScript(Class<T> iface, String script, String engineName) { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName(engineName); try {/*from www. j a v a 2 s. c o m*/ engine.eval(script); Invocable inv = (Invocable) engine; return inv.getInterface(iface); } catch (ScriptException e) { throw Util.newError(e, "Error while compiling script to implement " + iface + " SPI"); } }
From source file:com.pamarin.game24.Equations.java
private ScriptEngine getEngine() { if (engine == null) { ScriptEngineManager manager = new ScriptEngineManager(); engine = manager.getEngineByName("js"); }/*from w w w . ja v a 2s . co m*/ return engine; }
From source file:com.jkoolcloud.tnt4j.streams.filters.JavaScriptActivityExpressionFilter.java
@Override public boolean doFilter(ActivityInfo activityInfo) throws FilterException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName(JAVA_SCRIPT_LANG); if (CollectionUtils.isNotEmpty(exprVars)) { Object fValue;/*from w w w.j a v a2 s .c o m*/ String fieldName; for (String eVar : exprVars) { fieldName = eVar.substring(2, eVar.length() - 1); fValue = activityInfo.getFieldValue(fieldName); fieldName = placeHoldersMap.get(eVar); factory.put(StringUtils.isEmpty(fieldName) ? eVar : fieldName, fValue); } } try { boolean match = (boolean) engine.eval(StreamsScriptingUtils.addDefaultJSScriptImports(getExpression())); boolean filteredOut = isFilteredOut(getHandleType(), match); activityInfo.setFiltered(filteredOut); return filteredOut; } catch (Exception exc) { throw new FilterException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME, "ExpressionFilter.filtering.failed", filterExpression), exc); } }
From source file:com.intuit.karate.Script.java
public static ScriptValue evalInNashorn(String exp, ScriptContext context, ScriptValue selfValue, ScriptValue parentValue) {// w w w.j av a 2s . c om ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine nashorn = manager.getEngineByName("nashorn"); Bindings bindings = nashorn.getBindings(javax.script.ScriptContext.ENGINE_SCOPE); if (context != null) { Map<String, Object> map = context.getVariableBindings(); for (Map.Entry<String, Object> entry : map.entrySet()) { bindings.put(entry.getKey(), entry.getValue()); } bindings.put(ScriptContext.KARATE_NAME, new ScriptBridge(context)); } if (selfValue != null) { bindings.put(VAR_SELF, selfValue.getValue()); } if (parentValue != null) { bindings.put(VAR_DOLLAR, parentValue.getAfterConvertingFromJsonOrXmlIfNeeded()); } try { Object o = nashorn.eval(exp); ScriptValue result = new ScriptValue(o); logger.trace("nashorn returned: {}", result); return result; } catch (Exception e) { throw new RuntimeException("script failed: " + exp, e); } }
From source file:net.unit8.longadeseo.plugin.impl.JRubyExcelPlugin.java
public void init() { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("jruby"); Reader scriptReader = null;// w w w . j av a 2s .c o m try { if (scriptText == null || scriptText.length() == 0) { scriptReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(scriptFile)); script = ((Compilable) engine).compile(scriptReader); } else { script = ((Compilable) engine).compile(scriptText); } } catch (ScriptException e) { throw new PluginExecutionException(e); } finally { IOUtils.closeQuietly(scriptReader); } }
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 ww w .jav a 2 s .com @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")); }