List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Execute the Sass Compilation Ruby Script. * * @param sassScript//from www . j a v a 2 s. c om * the sass script * @throws MojoExecutionException * the mojo execution exception * @throws MojoFailureException * the mojo failure exception */ protected void executeSassScript(final String sassScript) throws MojoExecutionException, MojoFailureException { if (this.skip) { return; } final Log log = this.getLog(); System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe"); log.debug("Execute Sass Ruby script:\n\n" + sassScript + "\n\n"); final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby"); try { final CompilerCallback compilerCallback = new CompilerCallback(log); jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback); jruby.eval(sassScript); if (this.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); } log.debug("\n"); }
From source file:org.apache.camel.builder.script.ScriptBuilder.java
protected ScriptEngine createScriptEngine() { ScriptEngineManager manager = new ScriptEngineManager(); try {/*from ww w .ja v a 2 s .c om*/ engine = manager.getEngineByName(scriptEngineName); } catch (NoClassDefFoundError ex) { LOG.error("Cannot load the scriptEngine for " + scriptEngineName + ", the exception is " + ex + ", please ensure correct JARs is provided on classpath."); } if (engine == null) { throw new IllegalArgumentException("No script engine could be created for: " + getScriptEngineName()); } if (isPython()) { ScriptContext context = engine.getContext(); context.setAttribute("com.sun.script.jython.comp.mode", "eval", ScriptContext.ENGINE_SCOPE); } return engine; }
From source file:de.tor.tribes.ui.components.GroupSelectionList.java
private List<Village> getVillagesByEquation() { StringBuilder b = new StringBuilder(); boolean isFirst = true; List<Tag> relevantTags = new LinkedList<>(); for (int i = 1; i < getModel().getSize(); i++) { ListItem item = getItemAt(i);//w w w. j a va 2 s . com boolean ignore = false; if (!isFirst) { switch (item.getState()) { case NOT: b.append(" && !"); break; case AND: b.append(" && "); break; case OR: b.append(" || "); break; default: ignore = true; } } else { if (item.getState() == ListItem.RELATION_TYPE.DISABLED) {//ignore ignore = true; } else if (item.getState() == ListItem.RELATION_TYPE.NOT) {//NOT Tag 1 b.append("!"); isFirst = false; } else { isFirst = false; } } if (!ignore) { b.append(item.getTag().toString()).append(" "); relevantTags.add(item.getTag()); } } ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String baseEquation = b.toString(); List<Village> result = new LinkedList<>(); try { if (relevantVillages == null) { relevantVillages = GlobalOptions.getSelectedProfile().getTribe().getVillageList(); } for (Village v : relevantVillages) { String evaluationEquation = baseEquation; for (Tag tag : relevantTags) { evaluationEquation = evaluationEquation.replaceFirst(Pattern.quote(tag.toString()), Boolean.toString(tag.tagsVillage(v.getId()))); } engine.eval("var b = eval(\"" + evaluationEquation + "\")"); if ((Boolean) engine.get("b")) { result.add(v); } } } catch (Exception e) { //no result } return result; }
From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }/*from w w w . j a v a2s .co m*/ ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.apache.accumulo.shell.commands.ScriptCommand.java
@Override public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }// ww w.ja va 2 s .c o m ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:com.esri.gpt.catalog.search.SearchEngineRest.java
@Override public void doSearch() throws SearchException { Exception ex = null;/*from ww w . j a v a 2 s.c o m*/ try { URI uri = this.getConnectionUri(); URL url = uri.toURL(); HttpClientRequest clientRequest = HttpClientRequest.newRequest(HttpClientRequest.MethodName.GET, url.toExternalForm()); clientRequest.setConnectionTimeMs(getConnectionTimeoutMs()); clientRequest.setResponseTimeOutMs(getResponseTimeoutMs()); Map map = (Map) this.getRequestContext().extractFromSession(SEARCH_CREDENTIAL_MAP); if (map != null) { CredentialProvider credProvider = (CredentialProvider) map.get(this.getKey()); if (credProvider != null) { clientRequest.setCredentialProvider(credProvider); } } clientRequest.execute(); String response = clientRequest.readResponseAsCharacters(); InputStream is = null; try { SearchXslProfile profile = this.readXslProfile(); String js = Val.chkStr(profile.getResponsexslt()); //String js = Val.chkStr(this.getFactoryAttributes().get("searchResponseJsT")); String xml = null; if (js.toLowerCase().endsWith(".js")) { try { ResourcePath rPath = new ResourcePath(); URL fileUrl = rPath.makeUrl(js); is = fileUrl.openStream(); String jsTransFile = IOUtils.toString(is, "UTF-8"); jsTransFile = "var jsGptInput =" + response + ";" + jsTransFile; HttpServletRequest servletRequest = (HttpServletRequest) this.getRequestContext() .getServletRequest(); if (servletRequest != null) { jsTransFile = "var jsGptQueryString = '" + servletRequest.getQueryString() + "';" + jsTransFile; } jsTransFile = "var jsGptEndpointSearchQuery = '" + url.toExternalForm() + "';" + jsTransFile; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); //manager.put("jsGptInput", response); Object obj = engine.eval(jsTransFile); xml = obj.toString(); parseResponse(xml);// has to work before the finally. dont move } catch (Exception e) { throw new SearchException( e.getMessage() + ":" + "Error when doing transformation from javascript", e); } } else { xml = XmlIoUtil.jsonToXml(response, "gptJsonXml"); parseResponse(xml); } checkPagination(); } catch (SearchException e) { throw e; } catch (Exception e) { parseResponse(response); checkPagination(); } finally { if (is != null) { IOUtils.closeQuietly(is); } } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } finally { } if (ex != null) { throw new SearchException(ex.getMessage() + ": Could not perform search", ex); } }
From source file:org.pentaho.js.require.RequireJsGenerator.java
private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript) throws IOException, ScriptException, NoSuchMethodException, ParseException { moduleInfo = new ModuleInfo(moduleName, moduleVersion); Pattern pat = Pattern.compile("webjars!(.*).js"); Matcher m = pat.matcher(jsScript); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group(1)); }/*from w w w . j ava 2 s .co m*/ m.appendTail(sb); jsScript = sb.toString(); pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)"); m = pat.matcher(jsScript); while (m.find()) { m.appendReplacement(sb, m.group(2)); } m.appendTail(sb); jsScript = sb.toString(); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String script = IOUtils .toString(getClass().getResourceAsStream("/org/pentaho/js/require/require-js-aggregator.js")); script = script.replace("{{EXTERNAL_CONFIG}}", jsScript); engine.eval(script); requireConfig = (Map<String, Object>) parser .parse(((Invocable) engine).invokeFunction("processConfig", "").toString()); }
From source file:de.pixida.logtest.engine.Automaton.java
private void initScriptEngine() { final ScriptEngineManager manager = new ScriptEngineManager(); final String language = StringUtils.defaultIfBlank(this.scriptLanguage, DEFAULT_SCRIPTING_LANGUAGE); this.scriptingEngine = manager.getEngineByName(language); if (this.scriptingEngine == null) { final String msg = "Scripting engine for language '" + language + "' could not be initalized"; LOG.error(msg);/*from w w w . j av a 2s . c o m*/ throw new ExecutionException(msg); } else { LOG.debug("Using script language: {}", language); } this.scriptEnvironment = new ScriptEnvironment(); this.scriptingEngine.put("engine", this.scriptEnvironment); }
From source file:org.apache.solr.update.processor.StatelessScriptUpdateProcessorFactory.java
/** * Initializes a list of script engines - an engine per script file. * * @param req The solr request.//from w w w . j ava 2 s . c o m * @param rsp The solr response * @return The list of initialized script engines. */ private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp) throws SolrException { List<EngineInfo> scriptEngines = new ArrayList<>(); ScriptEngineManager scriptEngineManager = new ScriptEngineManager(resourceLoader.getClassLoader()); scriptEngineManager.put("logger", log); scriptEngineManager.put("req", req); scriptEngineManager.put("rsp", rsp); if (params != null) { scriptEngineManager.put("params", params); } for (ScriptFile scriptFile : scriptFiles) { ScriptEngine engine = null; if (null != engineName) { engine = scriptEngineManager.getEngineByName(engineName); if (engine == null) { String details = getSupportedEngines(scriptEngineManager, false); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by name: " + engineName + (null != details ? " -- supported names: " + details : "")); } } else { engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension()); if (engine == null) { String details = getSupportedEngines(scriptEngineManager, true); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by file extension: " + scriptFile.getFileName() + (null != details ? " -- supported extensions: " + details : "")); } } if (!(engine instanceof Invocable)) { String msg = "Engine " + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName())) + " does not support function invocation (via Invocable): " + engine.getClass().toString() + " (" + engine.getFactory().getEngineName() + ")"; log.error(msg); throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg); } if (scriptEngineCustomizer != null) { scriptEngineCustomizer.customize(engine); } scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile)); try { Reader scriptSrc = scriptFile.openReader(resourceLoader); try { engine.eval(scriptSrc); } catch (ScriptException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to evaluate script: " + scriptFile.getFileName(), e); } finally { IOUtils.closeQuietly(scriptSrc); } } catch (IOException ioe) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unable to evaluate script: " + scriptFile.getFileName(), ioe); } } return scriptEngines; }
From source file:org.pentaho.osgi.platform.webjars.utils.RequireJsGenerator.java
private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript) throws IOException, ScriptException, NoSuchMethodException, ParseException { moduleInfo = new ModuleInfo(moduleName, moduleVersion); Pattern pat = Pattern.compile("webjars!(.*).js"); Matcher m = pat.matcher(jsScript); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group(1)); }/*from ww w. j a v a 2s . co m*/ m.appendTail(sb); jsScript = sb.toString(); sb = new StringBuffer(); pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)"); m = pat.matcher(jsScript); while (m.find()) { m.appendReplacement(sb, m.group(2)); } m.appendTail(sb); jsScript = sb.toString(); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); String script = IOUtils.toString( getClass().getResourceAsStream("/org/pentaho/osgi/platform/webjars/require-js-aggregator.js")); script = script.replace("{{EXTERNAL_CONFIG}}", jsScript); engine.eval(script); requireConfig = (Map<String, Object>) parser .parse(((Invocable) engine).invokeFunction("processConfig", "").toString()); }