List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. From source file:com.servioticy.dispatcher.SOProcessor010.java
public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin, long timestamp) throws JsonParseException, JsonMappingException, IOException, ScriptException { Map<String, String> inputDocs = new HashMap<String, String>(); for (Map.Entry<String, SensorUpdate> inputSUEntry : inputSUs.entrySet()) { inputDocs.put(inputSUEntry.getKey(), this.mapper.writeValueAsString(inputSUEntry.getValue())); }/*from w ww . j a v a 2 s. c o m*/ PSOStream pstream = this.streams.get(streamId); if (!checkFilter(pstream.preFilter, inputDocs)) { return null; } ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); SensorUpdate su = new SensorUpdate(); su.setLastUpdate(timestamp); su.setChannels(new LinkedHashMap<String, SUChannel>()); int nulls = 0; for (Entry<String, PSOChannel> channelEntry : pstream.channels.entrySet()) { PSOChannel pchannel = channelEntry.getValue(); SUChannel suChannel = new SUChannel(); if (pchannel.currentValue == null) { suChannel.setCurrentValue(null); nulls++; } else { String currentValueCode = pchannel.currentValue.replace(inputDocs); Class type; String typeName; Object result = null; typeName = pchannel.type.toLowerCase(); if (typeName.equals("number")) { type = Double.class; } else if (typeName.equals("boolean")) { type = Boolean.class; } else if (typeName.equals("string")) { type = String.class; } else if (typeName.equals("geo_point")) { type = GeoPoint.class; } else { return null; } engine.eval("var result = JSON.stringify(" + currentValueCode + ")"); result = this.mapper.readValue((String) engine.get("result"), type); if (type == GeoPoint.class) result = ((GeoPoint) result).getLat() + "," + ((GeoPoint) result).getLon(); suChannel.setCurrentValue(result); } suChannel.setUnit(pchannel.unit); su.getChannels().put(channelEntry.getKey(), suChannel); } if (nulls >= su.getChannels().size()) { // This stream is mapping a Web Object. return null; } su.setTriggerPath(new ArrayList<ArrayList<String>>()); su.setPathTimestamps(new ArrayList<Long>()); this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); String resultSUDoc = this.mapper.writeValueAsString(su); if (!inputDocs.containsKey("result")) { inputDocs.put("result", resultSUDoc); } if (!checkFilter(pstream.postFilter, inputDocs)) { return null; } return su; }
From source file:org.openhab.binding.ebus.internal.parser.EBusConfigurationProvider.java
/** * Constructor/*from w ww.ja va 2s . com*/ */ public EBusConfigurationProvider() { final ScriptEngineManager mgr = new ScriptEngineManager(); // load script engine if available if (mgr != null) { final ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { logger.warn( "Unable to load \"JavaScript\" engine! Skip every eBus value calculated by JavaScript."); } else if (engine instanceof Compilable) { compEngine = (Compilable) engine; } } }
From source file:io.vertx.lang.js.JSVerticleFactory.java
private synchronized void init() { if (engine == null) { ScriptEngineManager mgr = new ScriptEngineManager(); engine = mgr.getEngineByName("nashorn"); if (engine == null) { throw new IllegalStateException( "Cannot find Nashorn JavaScript engine - maybe you are not running with Java 8 or later?"); }/*from ww w . j a va 2 s. co m*/ URL url = getClass().getClassLoader().getResource(JVM_NPM); if (url == null) { throw new IllegalStateException("Cannot find " + JVM_NPM + " on classpath"); } try (Scanner scanner = new Scanner(url.openStream(), "UTF-8").useDelimiter("\\A")) { String jvmNpm = scanner.next(); String jvmNpmPath = ClasspathFileResolver.resolveFilename(JVM_NPM); jvmNpm += "\n//# sourceURL=" + jvmNpmPath; engine.eval(jvmNpm); } catch (Exception e) { throw new IllegalStateException(e); } try { futureJSClass = (ScriptObjectMirror) engine.eval("require('vertx-js/future');"); // Put the globals in engine.put("__jvertx", vertx); String globs = "var Vertx = require('vertx-js/vertx'); var vertx = new Vertx(__jvertx);" + "var console = require('vertx-js/util/console');" + "var setTimeout = function(callback,delay) { return vertx.setTimer(delay, callback); };" + "var clearTimeout = function(id) { vertx.cancelTimer(id); };" + "var setInterval = function(callback, delay) { return vertx.setPeriodic(delay, callback); };" + "var clearInterval = clearTimeout;" + "var parent = this;" + "var global = this;"; if (ADD_NODEJS_PROCESS_ENV) { globs += "var process = {}; process.env=java.lang.System.getenv();"; } engine.eval(globs); } catch (ScriptException e) { throw new IllegalStateException("Failed to eval: " + e.getMessage(), e); } } }
From source file:org.jasig.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the SASS Compilation Ruby Script *///w w w .j a v a 2s.co 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:com.servioticy.dispatcher.SOProcessor020.java
public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin, long timestamp) throws IOException, ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); SensorUpdate su = new SensorUpdate(); su.setLastUpdate(timestamp);//ww w . j a v a2 s . c o m su.setChannels(new LinkedHashMap<String, SUChannel>()); SOStream stream = so.getStreams(this.mapper).get(streamId); for (Map.Entry<String, SOChannel> channelEntry : stream.getChannels().entrySet()) { SOChannel channel = channelEntry.getValue(); SUChannel suChannel = new SUChannel(); String currentValueCode = channel.getCurrentValue(); // TODO Check for invalid calls // TODO Check for an invalid header if (isFunction(currentValueCode)) { // There is no code for one of the channels. Invalid. return null; } else { TypeReference type; Class dataClass; boolean array = false; switch (parseType(channel.getType())) { case TYPE_ARRAY_NUMBER: type = new TypeReference<List<Double>>() { }; array = true; break; case TYPE_NUMBER: type = new TypeReference<Double>() { }; break; case TYPE_ARRAY_BOOLEAN: type = new TypeReference<List<Boolean>>() { }; array = true; break; case TYPE_BOOLEAN: type = new TypeReference<Boolean>() { }; break; case TYPE_ARRAY_STRING: type = new TypeReference<List<String>>() { }; array = true; break; case TYPE_STRING: type = new TypeReference<String>() { }; break; // non-primitive types case TYPE_ARRAY_GEOPOINT: type = new TypeReference<List<GeoPoint>>() { }; array = true; break; case TYPE_GEOPOINT: type = new TypeReference<GeoPoint>() { }; break; default: return null; } String resultVar = "$" + Long.toHexString(UUID.randomUUID().getMostSignificantBits()); engine.eval(initializationCode(inputSUs, origin) + "var " + resultVar + " = JSON.stringify(" + currentValueCode + "(" + functionArgsString(currentValueCode) + ")" + ")"); Object result = this.mapper.readValue((String) engine.get(resultVar), type); if (result == null) { // Filtered output. The type is not the expected one. return null; } suChannel.setCurrentValue(result); } suChannel.setUnit(channel.getUnit()); su.getChannels().put(channelEntry.getKey(), suChannel); } su.setTriggerPath(new ArrayList<ArrayList<String>>()); su.setPathTimestamps(new ArrayList<Long>()); return su; }
From source file:com.cubeia.ProtocolGeneratorMojo.java
private void generateCode(String lang, File protocolFile, File outputBaseDirectory, String packageName, boolean generateVisitors, String version, boolean failOnBadPacketOrder, String javascript_package_name) throws MojoExecutionException, MojoFailureException { if (append_language_to_output_base_dir) { outputBaseDirectory = appendLangToBaseDir(lang, outputBaseDirectory); getLog().info("Appended language '" + lang + "' to base dir, new base dir: " + outputBaseDirectory); }//www . ja v a2s.c o m ScriptEngineManager factory = new ScriptEngineManager(); // Create a JRuby engine. ScriptEngine engine = factory.getEngineByName("jruby"); // Evaluate JRuby code from string. InputStream scriptIn = getClass().getResourceAsStream(GENERATOR_WRAPPER_SCRIPT); if (scriptIn == null) { new MojoExecutionException( "unable to find code generator script resource: " + GENERATOR_WRAPPER_SCRIPT); } Object[] args = new Object[] { protocolFile.getPath(), lang, outputBaseDirectory.getPath(), packageName, generateVisitors ? "true" : null, version, failOnBadPacketOrder ? "true" : null, javascript_package_name }; InputStreamReader scriptReader = new InputStreamReader(scriptIn); try { engine.eval(scriptReader); Invocable invocableEngine = (Invocable) engine; invocableEngine.invokeFunction("generate_code", args); } catch (ScriptException e) { throw new MojoFailureException("code generation error: " + e.toString()); } catch (NoSuchMethodException e) { throw new MojoExecutionException("error calling code generator script: " + e.getMessage()); } }
From source file:org.elasticsearch.river.jolokia.strategy.simple.SimpleRiverSource.java
public void fetch(String hostname) { String url = "?"; String objectName = "?"; String[] attributeNames = new String[] {}; try {// ww w.jav a 2s . co m String catalogue = getCatalogue(hostname); String host = getHost(hostname); String port = getPort(hostname); String userName = getUser(hostname); String password = getPassword(hostname); url = getUrl((null == port ? host : (host + ":" + port)) + catalogue); objectName = setting.getObjectName(); Map<String, String> transforms = getAttributeTransforms(); attributeNames = getAttributeNames(); J4pClient j4pClient = useBasicAuth(userName, password) ? J4pClient.url(url).user(userName).password(password).build() : J4pClient.url(url).build(); J4pReadRequest req = new J4pReadRequest(objectName, attributeNames); logger.info("Executing {}, {}, {}", url, objectName, attributeNames); J4pReadResponse resp = j4pClient.execute(req); if (setting.getOnlyUpdates() && null != resp.asJSONObject().get("value")) { Integer oldValue = setting.getLastValueAsHash(); setting.setLastValueAsHash(resp.asJSONObject().get("value").toString().hashCode()); if (null != oldValue && oldValue.equals(setting.getLastValueAsHash())) { logger.info("Skipping " + objectName + " since no values has changed"); return; } } ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("rhino"); for (ObjectName object : resp.getObjectNames()) { StructuredObject reading = createReading(host, catalogue, getObjectName(object)); for (String attrib : attributeNames) { try { Object v = resp.getValue(object, attrib); // Transform if (transforms.containsKey(attrib)) { String function = transforms.get(attrib) .replaceFirst("^\\s*function\\s+([^\\s\\(]+)\\s*\\(.*$", "$1"); engine.eval(transforms.get(attrib)); v = convert(engine.eval(function + "(" + JSONValue.toJSONString(v) + ")")); } reading.source(setting.getPrefix() + attrib, v); } catch (Exception e) { reading.source(ERROR_PREFIX + setting.getPrefix() + attrib, e.getMessage()); } } createReading(reading); } } catch (Exception e) { try { logger.info("Failed to execute request {} {} {}", url, objectName, attributeNames, e); StructuredObject reading = createReading(getHost(hostname), getCatalogue(hostname), setting.getObjectName()); reading.source(ERROR_TYPE, e.getClass().getName()); reading.source(ERROR, e.getMessage()); int rc = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (e instanceof J4pRemoteException) { rc = ((J4pRemoteException) e).getStatus(); } reading.source(RESPONSE, rc); createReading(reading); } catch (Exception e1) { logger.error("Failed to store error message", e1); } } }
From source file:org.unitime.timetable.server.script.ScriptExecution.java
@Override protected void execute() throws Exception { org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try {//from w w w . j av a 2 s .c o m setStatus("Starting up...", 3); Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(script.getEngine()); engine.put("hibSession", hibSession); engine.put("session", SessionDAO.getInstance().get(getSessionId())); engine.put("log", this); incProgress(); engine.getContext().setWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) info(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); engine.getContext().setErrorWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) warn(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); incProgress(); debug("Engine: " + engine.getFactory().getEngineName() + " (ver. " + engine.getFactory().getEngineVersion() + ")"); debug("Language: " + engine.getFactory().getLanguageName() + " (ver. " + engine.getFactory().getLanguageVersion() + ")"); for (ScriptParameter parameter : script.getParameters()) { String value = iRequest.getParameters().get(parameter.getName()); if ("file".equals(parameter.getType()) && iFile != null) { debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)"); engine.put(parameter.getName(), iFile); continue; } if (value == null) value = parameter.getDefaultValue(); if (value == null) { engine.put(parameter.getName(), null); continue; } debug(parameter.getName() + ": " + value); if (parameter.getType().equalsIgnoreCase("boolean")) { engine.put(parameter.getName(), "true".equalsIgnoreCase(value)); } else if (parameter.getType().equalsIgnoreCase("long")) { engine.put(parameter.getName(), Long.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("int") || parameter.getType().equalsIgnoreCase("integer")) { engine.put(parameter.getName(), Integer.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("double")) { engine.put(parameter.getName(), Double.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("float")) { engine.put(parameter.getName(), Float.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("short")) { engine.put(parameter.getName(), Short.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("byte")) { engine.put(parameter.getName(), Byte.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("department")) { engine.put(parameter.getName(), DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("departments")) { List<Department> departments = new ArrayList<Department>(); for (String id : value.split(",")) if (!id.isEmpty()) departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), departments); } else if (parameter.getType().equalsIgnoreCase("subject")) { engine.put(parameter.getName(), SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("subjects")) { List<SubjectArea> subjects = new ArrayList<SubjectArea>(); for (String id : value.split(",")) if (!id.isEmpty()) subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), subjects); } else if (parameter.getType().equalsIgnoreCase("building")) { engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("buildings")) { List<Building> buildings = new ArrayList<Building>(); for (String id : value.split(",")) if (!id.isEmpty()) buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), buildings); } else if (parameter.getType().equalsIgnoreCase("room")) { engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("rooms")) { List<Room> rooms = new ArrayList<Room>(); for (String id : value.split(",")) if (!id.isEmpty()) rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), rooms); } else if (parameter.getType().equalsIgnoreCase("location")) { engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("locations")) { List<Location> locations = new ArrayList<Location>(); for (String id : value.split(",")) if (!id.isEmpty()) locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), locations); } else { engine.put(parameter.getName(), value); } } incProgress(); if (engine instanceof Compilable) { setStatus("Compiling script...", 1); CompiledScript compiled = ((Compilable) engine).compile(script.getScript()); incProgress(); setStatus("Running script...", 100); compiled.eval(); } else { setStatus("Running script...", 100); engine.eval(script.getScript()); } hibSession.flush(); tx.commit(); setStatus("All done.", 1); incProgress(); } catch (Exception e) { tx.rollback(); error("Execution failed: " + e.getMessage(), e); } finally { hibSession.close(); } }
From source file:org.okj.im.model.Member.java
/** * QQ// w w w. j a v a2 s.c om * @return */ public String getEncodePassword(AuthToken token) { if (StringUtils.isNotBlank(account.getPassword())) { InputStream in = null; try { in = ClassLoaderUtils.getResourceAsStream("encodePass.js", this.getClass()); Reader inreader = new InputStreamReader(in); ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine se = m.getEngineByName("javascript"); se.eval(inreader); Object t = se .eval("passwordEncoding(\"" + account.getPassword() + "\",\"" + token.getVerifycodeHex() + "\",\"" + StringUtils.upperCase(token.getVerifycode()) + "\");"); return t.toString(); } catch (Exception ex) { LogUtils.error(LOGGER, "", ex); } return account.getPassword(); } return account.getPassword(); }
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(); }/*from w w w .java2s . c o m*/ 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 ""; }