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:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldClearBindingsBetweenEvals() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); try {//from ww w. j ava 2 s. com engine.eval("g.V().has('name',s).next()"); fail("This should have failed because s is no longer bound"); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals(MissingPropertyException.class, t.getClass()); assertTrue(t.getMessage().startsWith("No such property: s for class")); } }
From source file:org.jasig.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the SASS Compilation Ruby Script *//* w w w . j a va2s .c o m*/ protected void executeSassScript(String sassScript) throws MojoExecutionException, MojoFailureException { final Log log = this.getLog(); System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe"); log.debug("Execute SASS Ruby Script:\n" + sassScript); final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby"); try { CompilerCallback compilerCallback = new CompilerCallback(log); jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback); jruby.eval(sassScript); if (failOnError && compilerCallback.hadError()) { throw new MojoFailureException("SASS compilation encountered errors (see above for details)."); } } catch (final ScriptException e) { throw new MojoExecutionException("Failed to execute SASS ruby script:\n" + sassScript, e); } }
From source file:org.tinymediamanager.scraper.util.YoutubeLinkExtractor.java
private String decryptSignature(String encryptedSignature) throws Exception { // first extract the player url and download the js player Matcher matcher = playerUrlPattern.matcher(jsonConfiguration); if (matcher.find()) { // only download the player javascript the first time if (StringUtils.isBlank(playerJavascript)) { Url jsPlayer = new Url("https:" + matcher.group(1).replaceAll("\\\\", "")); StringWriter writer = new StringWriter(); IOUtils.copy(jsPlayer.getInputStream(), writer, "UTF-8"); playerJavascript = writer.toString(); }/* w ww. j a v a 2 s . com*/ if (StringUtils.isBlank(playerJavascript)) { return ""; } // here comes the magic: extract the decrypt JS functions and translate them to Java :) matcher = patternDecryptFunction.matcher(playerJavascript); if (matcher.find()) { String decryptFunction = matcher.group(1); // extract relevant JS code String javaScript = extractJavascriptCode(playerJavascript, decryptFunction); // create a script engine manager ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(javaScript); Invocable inv = (Invocable) engine; // invoke the function to decrypt the signature String result = (String) inv.invokeFunction(decryptFunction, encryptedSignature); return result; } } return ""; }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldProperlyHandleBindings() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); Assert.assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); bindings.put("f", 0.5f); bindings.put("i", 1); bindings.put("b", true); bindings.put("l", 100l); bindings.put("d", 1.55555d); assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId("marko", "knows", "vadas")).next()); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval(/*ww w . j a v a 2 s . co m*/ "g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId("marko")).next()); }
From source file:de.ingrid.mdek.mapping.ScriptImportDataMapper.java
private void doMap(Map<String, Object> parameters) throws Exception { try {/* www .j a v a 2 s. co m*/ ScriptEngine engine = this.getScriptEngine(); // pass all parameters for (String param : parameters.keySet()) engine.put(param, parameters.get(param)); engine.put("log", log); // execute the mapping log.debug("Mapping with script: " + mapperScript); engine.eval(new InputStreamReader(mapperScript.getInputStream())); } catch (ScriptException e) { log.error("Error while evaluating the script!", e); throw e; } catch (IOException e) { log.error("Error while accessing the mapper script!", e); throw e; } }
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 av a2 s.c om*/ 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:cc.arduino.net.CustomProxySelector.java
private Proxy pacProxy(String pac, URI uri) throws IOException, ScriptException, NoSuchMethodException { setAuthenticator(preferences.get(Constants.PREF_PROXY_AUTO_USERNAME), preferences.get(Constants.PREF_PROXY_AUTO_PASSWORD)); URLConnection urlConnection = new URL(pac).openConnection(); urlConnection.connect();/* w w w . j av a 2 s .c om*/ if (urlConnection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection) urlConnection).getResponseCode(); if (responseCode != 200) { throw new IOException("Unable to fetch PAC file at " + pac + ". Response code is " + responseCode); } } String pacScript = new String(IOUtils.toByteArray(urlConnection.getInputStream()), Charset.forName("ASCII")); ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("pac", new PACSupportMethods()); Stream.of("isPlainHostName(host)", "dnsDomainIs(host, domain)", "localHostOrDomainIs(host, hostdom)", "isResolvable(host)", "isInNet(host, pattern, mask)", "dnsResolve(host)", "myIpAddress()", "dnsDomainLevels(host)", "shExpMatch(str, shexp)").forEach((fn) -> { try { nashorn.eval("function " + fn + " { return pac." + fn + "; }"); } catch (ScriptException e) { throw new RuntimeException(e); } }); nashorn.eval(pacScript); String proxyConfigs = callFindProxyForURL(uri, nashorn); return makeProxyFrom(proxyConfigs); }
From source file:org.opentestsystem.delivery.testreg.domain.constraintvalidators.JexlAssertValidator.java
@Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { Object evaluationResult;// ww w . ja v a 2 s. c om final ScriptEngine jexlScriptEngine = getJexlScriptEngine(); boolean hasValueInImplicitEligibilityRule = false; final boolean isImplicitEligibilityRule = value instanceof ImplicitEligibilityRule; if (isImplicitEligibilityRule) { final ImplicitEligibilityRule ierValue = (ImplicitEligibilityRule) value; hasValueInImplicitEligibilityRule = StringUtils.isNotBlank(ierValue.getValue()); } if (!isImplicitEligibilityRule || hasValueInImplicitEligibilityRule) { jexlScriptEngine.put(this.alias, value); try { evaluationResult = jexlScriptEngine.eval(this.script); } catch (final ScriptException e) { throw new ConstraintDeclarationException(e); } if (!(evaluationResult instanceof Boolean)) { throw new ConstraintDeclarationException("Evaluation Result should be a boolean type"); } return Boolean.TRUE.equals(evaluationResult); } return true; }
From source file:co.mcme.barry.listeners.ChatListener.java
@EventHandler(priority = EventPriority.MONITOR) public void onMathChat(AsyncPlayerChatEvent event) { if (event.getMessage().contains(".math")) { Player p = event.getPlayer();//from ww w.j a v a 2 s . c o m ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String[] msg = event.getMessage().split(" "); if (msg.length > 1) { try { List<String> list = new ArrayList<>(Arrays.asList(msg)); list.removeAll(Arrays.asList("", null, ".math")); String expression = StringUtils.join(list, " "); BarryPlugin.sendGlobalMessage("(" + ChatColor.DARK_AQUA + p.getName() + ChatColor.WHITE + ") " + expression + " = " + engine.eval(expression)); } catch (ScriptException ex) { b.sendTargetedMessage("I can't figure out that math problem.", p); } } else { b.sendTargetedMessage("I need to know what math to do", p); } } }
From source file:org.apache.nifi.scripting.ScriptEngineFactory.java
ScriptEngine getNewEngine(File scriptFile, String extension) throws ScriptException { ScriptEngine engine = scriptEngMgr.getEngineByExtension(extension); if (null == engine) { throw new IllegalArgumentException("No ScriptEngine exists for extension " + extension); }//from w ww .j av a2 s. co m // Initialize some paths StringBuilder sb = new StringBuilder(); switch (extension) { case "rb": String parent = scriptFile.getParent(); parent = StringUtils.replace(parent, "\\", "/"); sb.append("$:.unshift '").append(parent).append("'\n").append("$:.unshift File.join '").append(parent) .append("', 'lib'\n"); engine.eval(sb.toString()); break; case "py": parent = scriptFile.getParent(); parent = StringUtils.replace(parent, "\\", "/"); String lib = parent + "/lib"; sb.append("import sys\n").append("sys.path.append('").append(parent).append("')\n") .append("sys.path.append('").append(lib).append("')\n").append("__file__ = '") .append(scriptFile.getAbsolutePath()).append("'\n"); engine.eval(sb.toString()); break; default: break; } Object threading = engine.getFactory().getParameter(THREADING); // the MULTITHREADED status means that the scripts need to be careful about sharing state if (THREAD_ISOLATED.equals(threading) || STATELESS.equals(threading) || MULTITHREADED.equals(threading)) { // replace prior instance if any threadSafeEngines.put(extension, engine); } return engine; }