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:com.t_oster.visicut.misc.Helper.java
public static Double evaluateExpression(String expr) { expr = expr.replace(",", "."); try {// www .j a v a 2 s . com ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); expr = engine.eval(expr).toString(); } catch (Exception e) { //e.printStackTrace(); } return Double.parseDouble(expr); }
From source file:org.netbeans.jcode.core.util.FileUtil.java
public static String expandTemplate(String template, Map<String, Object> values) { StringWriter writer = new StringWriter(); ScriptEngine eng = getScriptEngine(); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); if (values != null) { bind.putAll(values);/*from w w w .j a va2s.c o m*/ } bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name()); eng.getContext().setWriter(writer); Reader is = new StringReader(template); try { eng.eval(is); } catch (ScriptException ex) { Exceptions.printStackTrace(ex); } return writer.toString(); }
From source file:io.github.jeddict.jcode.util.FileUtil.java
/** * In-memory template api//from www. j a v a 2s.c o m * * @param templateContent * @param values * @return */ public static String expandTemplateContent(String templateContent, Map<String, Object> values) { StringWriter writer = new StringWriter(); ScriptEngine eng = getScriptEngine(); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); if (values != null) { bind.putAll(values); } bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name()); eng.getContext().setWriter(writer); Reader is = new StringReader(templateContent); try { eng.eval(is); } catch (ScriptException ex) { Exceptions.printStackTrace(ex); } return writer.toString(); }
From source file:io.github.jeddict.jcode.util.FileUtil.java
public static String expandTemplate(String inputTemplatePath, Map<String, Object> values) { InputStream contentStream = loadResource(inputTemplatePath); StringWriter writer = new StringWriter(); ScriptEngine eng = getScriptEngine(); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); if (values != null) { bind.putAll(values);//from ww w.j a va2 s.c o m } bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name()); eng.getContext().setWriter(writer); Reader is = new InputStreamReader(contentStream); try { eng.eval(is); } catch (ScriptException ex) { Exceptions.printStackTrace(ex); } return writer.toString(); }
From source file:org.wso2.carbon.business.rules.core.util.TemplateManagerHelper.java
/** * Runs the script that is given as a string, and gives all the variables specified in the script * * @param script//from w w w .jav a2 s. c o m * @return Map of Strings * @throws TemplateManagerHelperException */ public static Map<String, String> getScriptGeneratedVariables(String script) throws RuleTemplateScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); ScriptContext scriptContext = new SimpleScriptContext(); scriptContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); try { // Run script engine.eval(script); Map<String, Object> returnedScriptContextBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); // Variable names and their values as strings, from the script context binding Map<String, String> scriptVariables = new HashMap<>(); for (Map.Entry scriptVariable : returnedScriptContextBindings.entrySet()) { if (scriptVariable.getValue() == null) { scriptVariables.put(scriptVariable.getKey().toString(), null); } else { scriptVariables.put(scriptVariable.getKey().toString(), scriptVariable.getValue().toString()); } } return scriptVariables; } catch (ScriptException e) { throw new RuleTemplateScriptException(e.getCause().getMessage(), e); } }
From source file:tk.tomby.tedit.services.ScriptingManager.java
/** * DOCUMENT ME!/* w w w . java 2 s . c om*/ * * @param lang DOCUMENT ME! * @param script DOCUMENT ME! * @param buffer DOCUMENT ME! */ public static Object exec(String lang, InputStream stream, IBuffer buffer) { Object result = null; BufferedReader reader = null; try { ScriptEngine engine = manager.getEngineByName(lang); reader = new BufferedReader(new InputStreamReader(stream)); if (buffer != null) { Bindings bindings = engine.createBindings(); bindings.put("buffer", new BufferDecorator(buffer)); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); } result = engine.eval(reader); } catch (ScriptException e) { log.error("error in script excution", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.warn("error closing reader", e); } } } return result; }
From source file:org.omegat.gui.scripting.ScriptRunner.java
/** * Execute a script with a given engine and bindings. * /*from ww w.j a v a 2 s . com*/ * @param script * The script in string form * @param engine * The engine * @param additionalBindings * A map of bindings that will be included along with other * bindings * @return The evaluation result * @throws ScriptException */ public static Object executeScript(String script, ScriptEngine engine, Map<String, Object> additionalBindings) throws ScriptException { // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"), // engine.getFactory().getEngineName())); Bindings bindings = engine.createBindings(); bindings.put(VAR_PROJECT, Core.getProject()); bindings.put(VAR_EDITOR, Core.getEditor()); bindings.put(VAR_GLOSSARY, Core.getGlossary()); bindings.put(VAR_MAINWINDOW, Core.getMainWindow()); bindings.put(VAR_CORE, Core.class); if (additionalBindings != null) { bindings.putAll(additionalBindings); } engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); Object result = engine.eval(script); if (engine instanceof Invocable) { invokeGuiScript((Invocable) engine); } return result; }
From source file:controllers.skilltag.SkillTagApp.java
@Transactional(readOnly = true) public static Result list() { DynamicForm requestData = Form.form().bindFromRequest(); String p = requestData.get("p") == null ? "1" : requestData.get("p"); Long i = StringUtils.isBlank(requestData.get("i")) ? 2L : Long.parseLong(requestData.get("i")); String s = StringUtils.isBlank(requestData.get("s")) ? null : requestData.get("s"); String cf = requestData.get("cf"); String ssf = requestData.get("ssf"); String ef = requestData.get("ef"); String gf = requestData.get("gf"); String o = requestData.get("o"); String ot = requestData.get("ot"); List<SkillTag> skillTags = SkillTag.getAll(i, 1, "all"); List<TagListVo> ivs = new ArrayList<TagListVo>(); List<TagListVo> svs = new ArrayList<TagListVo>(); ScriptEngine engine = SemUtils.getEngine(); try {/*from ww w. j av a 2s . co m*/ for (SkillTag st : skillTags) { TagListVo tv = new TagListVo(); tv.setTagName(st.tagName); tv.setTagId(st.id); if (st.tagType != null && st.tagType.ordinal() == SkillTag.TagType.CATEGORY.ordinal()) { if (st.id.equals(i)) tv.setIsCurr(true); tv.setHref(controllers.skilltag.routes.SkillTagApp.list().url() + "?p=1&i=" + tv.getTagId()); ivs.add(tv); } else { tv.setHref(controllers.skilltag.routes.SkillTagApp.list().url() + "?p=1&i=" + i + "&s=" + engine.eval("encodeURIComponent('" + tv.getTagName() + "')").toString()); svs.add(tv); } } if (StringUtils.isNotBlank(s)) { TagListVo tv = new TagListVo(); tv.setTagName(s); tv.setIsCurr(true); tv.setHref(controllers.skilltag.routes.SkillTagApp.list().url() + "?p=1&i=" + i + "&s=" + engine.eval("encodeURIComponent('" + tv.getTagName() + "')").toString()); svs.add(0, tv); } } catch (ScriptException e) { e.printStackTrace(); } List<ExpertListVO> elv = getTagExperts(p, i, s, cf, ssf, ef, gf, o, ot); SPage spage = new SPage(Integer.parseInt(p), i, s, cf, ssf, ef, gf, o, ot, ivs, svs, elv); List<String> countryList = SkillTag.getCountryNameWithCache(); spage.setCountryList(countryList); return ok(views.html.skilltag.skilltagall.render(spage)); }
From source file:io.apicurio.hub.core.js.OaiScriptEngineFactory.java
public static final ScriptEngine createScriptEngine(URL... jsUrls) throws Exception { logger.debug("Creating and initializing a Nashorn script engine."); long start = System.currentTimeMillis(); ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); if (engine == null) { throw new Exception("Failed to create a Nashorn script engine!"); }//from w w w . j a v a 2 s . c om URL consoleJsUrl = OaiScriptEngineFactory.class.getClassLoader().getResource("js-lib/core-console.js"); if (consoleJsUrl == null) { throw new Exception("Failed to load script: core-console.js"); } URL oaiJsUrl = OaiScriptEngineFactory.class.getClassLoader().getResource("js-lib/OAI.umd.js"); if (oaiJsUrl == null) { throw new Exception("Failed to load script: OAI.umd.js"); } URL oaiCommandsJsUrl = OaiScriptEngineFactory.class.getClassLoader() .getResource("js-lib/OAI-commands.umd.js"); if (oaiCommandsJsUrl == null) { throw new Exception("Failed to load script: OAI-commands.umd.js"); } // Load the JS libraries into the engine engine.eval(IOUtils.toString(consoleJsUrl)); engine.eval(IOUtils.toString(oaiJsUrl)); engine.eval(IOUtils.toString(oaiCommandsJsUrl)); for (URL jsUrl : jsUrls) { engine.eval(IOUtils.toString(jsUrl)); } long end = System.currentTimeMillis(); logger.debug("Initialized a Nashorn script engine in {} millis.", end - start); return engine; }
From source file:com.datatorrent.stram.client.StramClientUtils.java
public static void evalProperties(Properties target, Configuration vars) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); Pattern substitutionPattern = Pattern.compile("\\$\\{(.+?)\\}"); Pattern evalPattern = Pattern.compile("\\{% (.+?) %\\}"); try {/*w w w . j ava 2 s. c o m*/ engine.eval("var _prop = {}"); for (Map.Entry<String, String> entry : vars) { String evalString = String.format("_prop[\"%s\"] = \"%s\"", StringEscapeUtils.escapeJava(entry.getKey()), StringEscapeUtils.escapeJava(entry.getValue())); engine.eval(evalString); } } catch (ScriptException ex) { LOG.warn("Javascript error: {}", ex.getMessage()); } for (Map.Entry<Object, Object> entry : target.entrySet()) { String value = entry.getValue().toString(); Matcher matcher = substitutionPattern.matcher(value); if (matcher.find()) { StringBuilder newValue = new StringBuilder(); int cursor = 0; do { newValue.append(value.substring(cursor, matcher.start())); String subst = vars.get(matcher.group(1)); if (subst != null) { newValue.append(subst); } cursor = matcher.end(); } while (matcher.find()); newValue.append(value.substring(cursor)); target.put(entry.getKey(), newValue.toString()); } matcher = evalPattern.matcher(value); if (matcher.find()) { StringBuilder newValue = new StringBuilder(); int cursor = 0; do { newValue.append(value.substring(cursor, matcher.start())); try { Object result = engine.eval(matcher.group(1)); String eval = result.toString(); if (eval != null) { newValue.append(eval); } } catch (ScriptException ex) { LOG.warn("JavaScript exception {}", ex.getMessage()); } cursor = matcher.end(); } while (matcher.find()); newValue.append(value.substring(cursor)); target.put(entry.getKey(), newValue.toString()); } } }