List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. From source file:net.landora.video.filerenaming.RenameScriptManager.java
RenamingScript createRenamingScript(String folderScript, String fileScript, boolean reportExceptions) { try {// ww w .j a v a2s.c o m StringBuilder str = new StringBuilder(); str.append(getClassScript("RenameScript.py")); str.append("\n"); str.append(createScript("findFolderName", folderScript)); str.append("\n"); str.append(createScript("findFilename", fileScript)); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("jython"); engine.eval(str.toString()); Invocable inv = (Invocable) engine; return inv.getInterface(RenamingScript.class); } catch (Exception ex) { if (reportExceptions) { LoggerFactory.getLogger(getClass()).error("Error getting rename script.", ex); } return null; } }
From source file:cz.vity.freerapid.plugins.services.webshare.PasswordJS.java
public String encryptPassword(String pass, String salt) throws Exception { try {/*w w w . jav a 2 s . com*/ ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); if (engine == null) throw new RuntimeException("JavaScript engine not found"); final String md5enc = (String) engine .eval(JavaScript_MD5Crypt + "md5crypt(\"" + pass + "\", \"" + salt + "\")"); return DigestUtils.shaHex(md5enc); } catch (Exception e) { throw new ServiceConnectionProblemException("Can't execute javascript"); } }
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 w w w . j av a 2 s .c om 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:com.orange.clara.cloud.servicedbdumper.config.CatalogConfig.java
private float getCostFromQuota(String quota, String formula) throws ParseException, ScriptException { long size = ByteFormat.parse(quota); String formulaInjected = formula.replaceAll("quota", String.valueOf(size * this.getDefaultCost())); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); Object eval = engine.eval(formulaInjected); if (eval instanceof Integer) { return new Float((Integer) eval); }//w w w . ja v a 2s . c o m if (eval instanceof Float) { return (Float) eval; } return Math.round((Double) eval); }
From source file:com.blackbear.flatworm.config.ScriptletBO.java
/** * Constructor for ScriptIdentityImpl that attempts to load the Script Engine specified by name. * * @param scriptEngineName The name of the script engine to load. If {@code null} the {@code ScriptletBO.DEFAULT_SCRIPT_ENGINE} is * used./*from w w w. j a v a2s. c o m*/ * @param functionName The name of the function in the script that should be executed - the {@link * com.blackbear.flatworm.FileFormat} instance will be the only parameter sent to the function specified. If the * {@code functionName} is {@code null} then the {@code ScriptIdentityImp.DEFAULT_SCRIPT_IDENTITY_FUNCTION_NAME} value will be * used. * @throws FlatwormConfigurationException should the script be invalid or should the {@code scriptEngineName} not resolve to a valid * script engine. */ public ScriptletBO(String scriptEngineName, String functionName) throws FlatwormConfigurationException { this.scriptEngineName = StringUtils.isBlank(scriptEngineName) ? DEFAULT_SCRIPT_ENGINE : scriptEngineName; this.functionName = StringUtils.isBlank(functionName) ? ScriptIdentityImpl.DEFAULT_SCRIPT_IDENTITY_FUNCTION_NAME : functionName; ScriptEngineManager engineManager = new ScriptEngineManager(); scriptEngine = engineManager.getEngineByName(this.scriptEngineName); if (scriptEngine == null) { throw new FlatwormConfigurationException(String .format("The %s ScriptEngine could not be found by the given name.", this.scriptEngineName)); } else { scriptInvocable = (Invocable) scriptEngine; } }
From source file:it.delli.mwebc.command.impl.EventCommand.java
public void execute(Page page, JsonObject data) { String eventName = data.get("event").getAsString(); String eventType = data.get("eventType").getAsString(); String method = data.get("forward").getAsString(); Widget widget = null;//from w w w . j a va 2 s . co m EventListener eventListener = null; if (data.get("id") != null) { widget = page.getWidget(data.get("id").getAsString()); eventListener = widget.getEventListener(eventName); } else { eventListener = page.getEventListener(); } Class eventTypeClass = page.getApplication().getEventClass(eventType); Event event = null; try { event = (Event) eventTypeClass.getConstructor(String.class, Widget.class, JsonObject.class) .newInstance(eventName, widget, data.get("data").getAsJsonObject()); } catch (Exception e) { log.error("Exception in creating event instance for event type " + eventType); } ; event.setPage(page); // bind widgets ReflectionUtils.bindWidgets(eventListener, page); // Method forwardMethod = null; if (eventListener instanceof PageEventListener && page.getWidget(method) != null) { try { it.delli.mwebc.widget.Method widgetMethod = (it.delli.mwebc.widget.Method) page.getWidget(method); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("groovy"); engine.put("eventListener", null); engine.eval(widgetMethod.getScript()); eventListener = (EventListener) engine.get("eventListener"); forwardMethod = eventListener.getClass().getMethod(method, Event.class); forwardMethod.setAccessible(true); } catch (Exception e) { log.error("Exception in getting method to execute", e); } } else { try { forwardMethod = eventListener.getClass().getMethod(method, Event.class); forwardMethod.setAccessible(true); } catch (Exception e) { log.error("Exception in getting method to execute", e); } } if (forwardMethod != null) { if (event.getWidget() != null) { log.info("Executing forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName() + " on widget " + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")"); } else { log.info("Executing forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName()); } try { forwardMethod.invoke(eventListener, event); } catch (Exception e) { if (event.getWidget() != null) { log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName() + " on widget " + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")", e); } else { log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "." + forwardMethod.getName() + " for event " + event.getName(), e); } log.error("Exception in forward method execution", e); } } else { log.info("Forward method does not exist in event listener " + eventListener.getClass().getName() + " for event " + event.getName()); log.info("Notifying end of failed execution for event " + event.getName()); } }
From source file:org.openhab.binding.ebus.parser.EBusConfigurationProvider.java
/** * Constructor// www. j a v a2 s . c o m */ public EBusConfigurationProvider() { final ScriptEngineManager mgr = new ScriptEngineManager(); 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:com.seajas.search.profiler.validator.ModifierValidator.java
/** * Validate the given command object.//from w w w. j a va 2 s. c o m * * @param command * @param errors */ @Override public void validate(final Object command, final Errors errors) { ModifierCommand modifier = (ModifierCommand) command; if (modifier.getAction() != null && (modifier.getAction().equals("add") || modifier.getAction().equals("edit"))) { if (StringUtils.isEmpty(modifier.getUrlExpression())) errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.empty"); else try { Pattern.compile(modifier.getUrlExpression()); } catch (PatternSyntaxException e) { errors.rejectValue("urlExpression", "modifiers.validator.error.url.expression.invalid"); } if (StringUtils.isEmpty(modifier.getUrlType())) errors.rejectValue("urlType", "modifiers.validator.error.url.type.empty"); } else if (modifier.getFilterAction() != null && (modifier.getFilterAction().equals("add-filter") || modifier.getFilterAction().equals("edit-filter"))) { if (StringUtils.isEmpty(modifier.getFilterStart())) errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.empty"); else if (modifier.getFilterAsExpression()) try { Pattern.compile(modifier.getFilterStart()); } catch (PatternSyntaxException e) { errors.rejectValue("filterStart", "modifiers.validator.error.filter.start.invalid"); } if (StringUtils.isEmpty(modifier.getFilterEnd())) errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.empty"); else if (modifier.getFilterAsExpression()) try { Pattern.compile(modifier.getFilterEnd()); } catch (PatternSyntaxException e) { errors.rejectValue("filterEnd", "modifiers.validator.error.filter.end.invalid"); } } else if (modifier.getScriptAction() != null && (modifier.getScriptAction().equals("add-script") || modifier.getScriptAction().equals("edit-script"))) { if (StringUtils.isEmpty(modifier.getScriptLanguage())) errors.rejectValue("scriptLanguage", "modifiers.validator.error.script.language.invalid"); if (StringUtils.isEmpty(modifier.getScriptContent())) errors.rejectValue("scriptContent", "modifiers.validator.error.script.content.empty"); else { if (modifier.getScriptLanguage().equalsIgnoreCase("xslt")) { StreamSource source = new StreamSource(new StringReader(modifier.getScriptContent())); try { TransformerFactory.newInstance().newTransformer(source); } catch (Exception e) { errors.rejectValue("scriptContent", "modifiers.validator.error.script.content.invalid.transformation"); } } else { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName(modifier.getScriptLanguage().toLowerCase()); engine.put("input", ""); engine.put("inputUrl", ""); engine.put("inputMaximumContentLength", 0L); try { engine.eval(modifier.getScriptContent()); } catch (ScriptException e) { errors.rejectValue("scriptContent", "modifiers.validator.error.script.content.syntax.error"); logger.warn("Script validation failed", e); } } } } }
From source file:org.jspringbot.keyword.json.JSONHelper.java
public int getJsonListLength(String jsonExpression) { validate();/*from w ww .j a v a 2 s. co m*/ try { ScriptEngineManager manager = new ScriptEngineManager(); engine = manager.getEngineByName("JavaScript"); engine.eval("var json = " + jsonString + ";"); engine.eval("var jsonExpr = json." + jsonExpression + ".length;"); int length = ((Number) engine.get("jsonExpr")).intValue(); LOG.createAppender().appendBold("Get JSON List Length:") .appendProperty("Json Expression", jsonExpression).appendProperty("Length", length).log(); return length; } catch (Exception e) { throw new IllegalStateException("Response is not json.", e); } }
From source file:org.springframework.data.hadoop.scripting.Jsr223ScriptEvaluator.java
protected ScriptEngine discoverEngine(ScriptSource script, Map<String, Object> arguments) { ScriptEngineManager engineManager = new ScriptEngineManager(classLoader); ScriptEngine engine = null;/*from w w w .j av a2s.com*/ if (StringUtils.hasText(language)) { engine = engineManager.getEngineByName(language); } else { // make use the extension (enhanced ScriptSource interface) Assert.hasText(extension, "no language or extension specified"); engine = engineManager.getEngineByExtension(extension); } Assert.notNull(engine, "No suitable engine found for " + (StringUtils.hasText(language) ? "language " + language : "extension " + extension)); if (log.isDebugEnabled()) { ScriptEngineFactory factory = engine.getFactory(); log.debug(String.format("Using ScriptEngine %s (%s), language %s (%s)", factory.getEngineName(), factory.getEngineVersion(), factory.getLanguageName(), factory.getLanguageVersion())); } return engine; }