List of usage examples for javax.script ScriptEngineManager ScriptEngineManager
public ScriptEngineManager()
ScriptEngineManager(Thread.currentThread().getContextClassLoader())
. From source file:de.ingrid.mdek.mapping.ScriptImportDataMapper.java
/** * Get the script engine (JavaScript). It returns always the same instance once initialized. * // www .j av a2 s. c o m * @return script engine. */ protected ScriptEngine getScriptEngine() { if (engine == null) { ScriptEngineManager manager = new ScriptEngineManager(); engine = manager.getEngineByName("JavaScript"); } return engine; }
From source file:org.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper.java
public static Object eval(Message message, ComponentContext context, ModelAttribute attribute, Object value, ModelEntity entity, EntityData data, String expression) { ScriptEngine engine = scriptEngine.get(); if (engine == null) { ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByName("groovy"); scriptEngine.set(engine);// www . j a v a 2 s . co m } engine.put("value", value); engine.put("data", data); engine.put("entity", entity); engine.put("attribute", attribute); engine.put("message", message); engine.put("context", context); try { String importString = "import org.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper;\n"; String code = String.format( "return new ModelAttributeScriptHelper(message, context, attribute, entity, data, value) { public Object eval() { return %s } }.eval()", expression); return engine.eval(importString + code); } catch (ScriptException e) { throw new RuntimeException("Unable to evaluate groovy script. Attribute ==> " + attribute.getName() + ". Value ==> " + value.toString() + "." + e.getCause().getMessage(), e); } }
From source file:org.metamorphosis.core.ModuleManager.java
public Object buildAction(String url) throws Exception { Module module = getCurrentModule();/*from w ww . jav a 2 s. c om*/ if (module != null) { Action action = module.getAction(url); if (action != null && action.getScript() != null) { File script = new File(module.getFolder() + "/scripts/" + action.getScript()); if (script.exists()) { String name = script.getName(); String extension = name.substring(name.indexOf(".") + 1); ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(extension); return engine.eval(new FileReader(script)); } } } return null; }
From source file:com.tc.websocket.scripts.Script.java
/** * Prints the engines.//from w w w .j a v a 2 s . c o m */ public static void printEngines() { ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> engines = manager.getEngineFactories(); for (ScriptEngineFactory engine : engines) { System.out.println(engine.getEngineName()); } }
From source file:com.intuit.karate.Script.java
public static ScriptValue evalInNashorn(String exp, ScriptContext context, ScriptValue selfValue, ScriptValue parentValue) {/*from w w w. j av a 2 s . com*/ 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: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 w ww. j av a 2 s.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: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);/*from w w w.java 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:com.esri.gpt.catalog.search.SearchEngineRest.java
@Override public void doSearch() throws SearchException { Exception ex = null;/* w w w .j a va 2 s . co 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.siphon.common.js.JsEngineUtil.java
public static ScriptEngine newEngine() { ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); initEngine(engine, new Object[] {}); return engine; }
From source file:reactor.js.core.json.Microbench.java
@Setup public void init() throws ScriptException, JsonParseException, JsonMappingException, IOException { scriptEngine = new ScriptEngineManager().getEngineByName("nashorn"); scriptEngine.put("json", json); scriptEngine.put("Object_class", Object.class); scriptEngine.put("largeJson", largeJson); scriptEngine.put("mapper", mapper); scriptEngine.eval("var REACTOR = Java.type('reactor.js.core.json.JsonFunctions');"); scriptEngine.eval("var JACKSON = Java.type('com.pivotal.cf.mobile.ats.json.JsonFunctions');"); scriptEngine.eval(//from w w w . j av a 2s.c o m "var jsObj = [{date: new Date(),integer:1,float:1.01,boolean:true,obj:{str:'foobar'},arr:[true,false,null,undefined]}];"); scriptEngine.eval("var mecObj = JSON.parse(largeJson)"); }