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.inkubator.hrm.service.impl.PayTempKalkulasiServiceImpl.java
@Override @Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public void executeBatchFinalSalaryCalculation(EmpData empData) throws ScriptException { PayTempKalkulasiEmpPajak tax_23 = payTempKalkulasiEmpPajakDao .getEntityByEmpDataIdAndTaxComponentId(empData.getId(), 23L); PayTempKalkulasi taxKalkulasi = payTempKalkulasiDao .getEntityByEmpDataIdAndSpecificModelComponent(empData.getId(), HRMConstant.MODEL_COMP_TAX); //jika pajak PPh pasal 21 kurang dari 0(minus), maka di set 0 saja di payTempKalkulasi if (tax_23.getNominal() > 0) { taxKalkulasi.setNominal(new BigDecimal(tax_23.getNominal())); } else {/*from w w w .j av a2s .c om*/ taxKalkulasi.setNominal(new BigDecimal(0)); } payTempKalkulasiDao.update(taxKalkulasi); PayTempKalkulasi ceilKalkulasi = payTempKalkulasiDao .getEntityByEmpDataIdAndSpecificModelComponent(empData.getId(), HRMConstant.MODEL_COMP_CEIL); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); double ceiling = (Double) jsEngine.eval(ceilKalkulasi.getPaySalaryComponent().getFormula()); PayTempKalkulasi totalIncomeKalkulasi = payTempKalkulasiDao.getEntityByEmpDataIdAndSpecificModelComponent( empData.getId(), HRMConstant.MODEL_COMP_TAKE_HOME_PAY); BigDecimal totalIncome = totalIncomeKalkulasi.getNominal(); totalIncome = this.calculateTotalIncome(totalIncome, taxKalkulasi); //dapatkan nilai sisa/pembulatan BigDecimal val[] = totalIncome.divideAndRemainder(new BigDecimal(ceiling)); ceilKalkulasi.setNominal(val[1]); payTempKalkulasiDao.update(ceilKalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, ceilKalkulasi); totalIncomeKalkulasi.setNominal(totalIncome); payTempKalkulasiDao.update(totalIncomeKalkulasi); }
From source file:tk.elevenk.restfulrobot.testcase.TestCase.java
/** * Runs the given test script file/* w ww . j a v a2 s . com*/ * * @param fileName */ public void runScript(String fileName) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript"); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); if (!fileName.endsWith(".js")) { fileName = fileName.concat(".js"); } FileReader scriptFile = null; // attempt to open the script file try { scriptFile = new FileReader(new File(RestfulRobot.SCRIPTS_PATH + fileName)); } catch (FileNotFoundException e) { logger.error(ExceptionUtils.getStackTrace(e)); result.setDetails(e.getMessage()); result.setResultType(TestResult.TYPE_ERROR); } // run the script try { logger.info("Running script " + fileName); engine.eval(scriptFile); } catch (ScriptException e) { logger.error(ExceptionUtils.getStackTrace(e)); result.setDetails(e.getMessage()); result.setResultType(TestResult.TYPE_ERROR); } // pull data from script try { this.testCaseID = (String) engine.get("testCaseID"); this.testCategory = (String) engine.get("testCategory"); this.testPlan = (String) engine.get("testPlan"); this.testProject = (String) engine.get("testProject"); this.testType = (String) engine.get("testType"); this.testName = (String) engine.get("testName"); } catch (Exception e) { // TODO make this try each parameter } logger.info("Finished running script"); }
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 www. j av a 2 s. c om*/ 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()); }
From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java
@Override public boolean checkPermission(DocumentModel doc, String xpath, Blob blob, String reason, Map<String, Serializable> extendedInfos) { List<DownloadPermissionDescriptor> descriptors = registry.getDownloadPermissionDescriptors(); if (descriptors.isEmpty()) { return true; }//from ww w. j a v a 2s . c o m xpath = fixXPath(xpath); Map<String, Object> context = new HashMap<>(); Map<String, Serializable> ei = extendedInfos == null ? Collections.emptyMap() : extendedInfos; NuxeoPrincipal currentUser = ClientLoginModule.getCurrentPrincipal(); context.put("Document", doc); context.put("XPath", xpath); context.put("Blob", blob); context.put("Reason", reason); context.put("Infos", ei); context.put("Rendition", ei.get("rendition")); context.put("CurrentUser", currentUser); for (DownloadPermissionDescriptor descriptor : descriptors) { ScriptEngine engine = scriptEngineManager.getEngineByName(descriptor.getScriptLanguage()); if (engine == null) { throw new NuxeoException("Engine not found for language: " + descriptor.getScriptLanguage() + " in permission: " + descriptor.getName()); } if (!(engine instanceof Invocable)) { throw new NuxeoException("Engine " + engine.getClass().getName() + " not Invocable for language: " + descriptor.getScriptLanguage() + " in permission: " + descriptor.getName()); } Object result; try { engine.eval(descriptor.getScript()); engine.getBindings(ScriptContext.ENGINE_SCOPE).putAll(context); result = ((Invocable) engine).invokeFunction(RUN_FUNCTION); } catch (NoSuchMethodException e) { throw new NuxeoException("Script does not contain function: " + RUN_FUNCTION + "() in permission: " + descriptor.getName(), e); } catch (ScriptException e) { log.error("Failed to evaluate script: " + descriptor.getName(), e); continue; } if (!(result instanceof Boolean)) { log.error("Failed to get boolean result from permission: " + descriptor.getName() + " (" + result + ")"); continue; } boolean allow = ((Boolean) result).booleanValue(); if (!allow) { return false; } } return true; }
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 ww . j a v a2s. co m 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.ngrinder.operation.cotroller.ScriptConsoleController.java
/** * Run the given script. The run result is stored in "result" of the given model. * * @param script script//w ww. j a v a 2 s .c o m * @param model model * @return operation/script_console */ @RequestMapping("") public String run(@RequestParam(value = "script", defaultValue = "") String script, Model model) { if (StringUtils.isNotBlank(script)) { ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy"); engine.put("applicationContext", this.applicationContext); engine.put("agentManager", this.agentManager); engine.put("agentManagerService", this.agentManagerService); engine.put("regionService", this.regionService); engine.put("consoleManager", this.consoleManager); engine.put("userService", this.userService); engine.put("perfTestService", this.perfTestService); engine.put("tagService", this.tagService); engine.put("fileEntryService", this.fileEntryService); engine.put("config", getConfig()); engine.put("pluginManager", this.pluginManager); engine.put("cacheManager", this.cacheManager); engine.put("user", getCurrentUser()); final StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); engine.getContext().setWriter(writer); engine.getContext().setErrorWriter(writer); try { Object result = engine.eval(script); result = out.toString() + "\n" + ObjectUtils.defaultIfNull(result, ""); model.addAttribute("result", result); } catch (ScriptException e) { model.addAttribute("result", out.toString() + "\n" + e.getMessage()); } } model.addAttribute("script", script); return "operation/script_console"; }
From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.DataFactoryScriptingSupport.java
public void initialize(final DataFactory dataFactory, final DataFactoryContext dataFactoryContext) throws ReportDataFactoryException { if (globalScriptContext != null) { return;/*from www . ja v a 2 s . c o m*/ } this.dataFactory = dataFactory; this.resourceManager = dataFactoryContext.getResourceManager(); this.contextKey = dataFactoryContext.getContextKey(); this.configuration = dataFactoryContext.getConfiguration(); this.resourceBundleFactory = dataFactoryContext.getResourceBundleFactory(); this.dataFactoryContext = dataFactoryContext; globalScriptContext = new SimpleScriptContext(); globalScriptContext.setAttribute("dataFactory", dataFactory, ScriptContext.ENGINE_SCOPE); globalScriptContext.setAttribute("configuration", configuration, ScriptContext.ENGINE_SCOPE); globalScriptContext.setAttribute("resourceManager", resourceManager, ScriptContext.ENGINE_SCOPE); globalScriptContext.setAttribute("contextKey", contextKey, ScriptContext.ENGINE_SCOPE); globalScriptContext.setAttribute("resourceBundleFactory", resourceBundleFactory, ScriptContext.ENGINE_SCOPE); if (StringUtils.isEmpty(globalScriptLanguage)) { return; } globalScriptContext.setAttribute("scriptHelper", new ScriptHelper(globalScriptContext, globalScriptLanguage, resourceManager, contextKey), ScriptContext.ENGINE_SCOPE); final ScriptEngine maybeInvocableEngine = new ScriptEngineManager().getEngineByName(globalScriptLanguage); if (maybeInvocableEngine == null) { throw new ReportDataFactoryException(String.format( "DataFactoryScriptingSupport: Failed to locate scripting engine for language '%s'.", globalScriptLanguage)); } if (maybeInvocableEngine instanceof Invocable == false) { return; } this.globalScriptEngine = (Invocable) maybeInvocableEngine; maybeInvocableEngine.setContext(globalScriptContext); try { maybeInvocableEngine.eval(globalScript); } catch (ScriptException e) { throw new ReportDataFactoryException( "DataFactoryScriptingSupport: Failed to execute datafactory init script.", e); } }
From source file:org.pentaho.platform.plugin.condition.scriptable.ScriptableCondition.java
public boolean shouldExecute(final Map currentInputs, final Log logger) throws Exception { boolean shouldExecute = this.getDefaultResult(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName(this.getScriptLanguage()); if (engine == null) { throw new IllegalArgumentException(Messages.getInstance().getErrorString( "ScriptableCondition.ERROR_0001_ENGINE_NOT_AVAILABLE", this.getScriptLanguage())); //$NON-NLS-1$ }/* w w w. j av a 2 s . c om*/ Object inputValue; IActionParameter inputParameter; String inputName = null; Iterator inputs = currentInputs.entrySet().iterator(); Map.Entry mapEntry; while (inputs.hasNext()) { mapEntry = (Map.Entry) inputs.next(); inputName = (String) mapEntry.getKey(); if (this.getIgnoreInputNamesWithMinus() && inputName.indexOf('-') >= 0) { logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_IGNORED_INPUT", inputName)); //$NON-NLS-1$ continue; } inputParameter = (IActionParameter) mapEntry.getValue(); inputValue = inputParameter.getValue(); engine.put(inputName, inputValue); // What happens to resultset objects I wonder... } engine.put("out", System.out); engine.put("rule", this); Object resultObject = engine.eval(this.getScript()); if (resultObject instanceof Boolean) { return ((Boolean) resultObject).booleanValue(); } else if (resultObject instanceof String) { return ("true".equalsIgnoreCase(resultObject.toString())) || ("yes".equalsIgnoreCase(resultObject.toString())); //$NON-NLS-1$ //$NON-NLS-2$ } else if (resultObject instanceof Number) { return ((Number) resultObject).intValue() > 0; } else if (resultObject instanceof IPentahoResultSet) { return ((IPentahoResultSet) resultObject).getRowCount() > 0; } logger.info(Messages.getInstance().getString("ScriptableCondition.INFO_DEFAULT_RESULT_RETURNED")); //$NON-NLS-1$ return shouldExecute; }
From source file:org.ms123.common.utils.UtilsServiceImpl.java
public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception { System.out.println("UtilsServiceImpl.executeScript:" + params); String storeId = (String) params.get("storeId"); StoreDesc sdesc = StoreDesc.get(storeId); namespace = sdesc.getNamespace();/*from www . ja v a 2 s . com*/ System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace); ScriptEngine se = m_scriptEngineService.getEngineByName("groovy"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); se.getContext().setWriter(pw); Bindings b = se.createBindings(); b.putAll(params); b.put("jdo", m_dataLayer); b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService")); b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService")); b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService")); b.put("storeDesc", sdesc); b.put("home", System.getProperty("simpl4.dir")); b.put("log", m_logger); b.put("user", user); b.put("namespace", namespace); se.setBindings(b, ScriptContext.ENGINE_SCOPE); b.put("se", se); Object r = ""; FileReader fr = getScriptFile(namespace, scriptName); r = se.eval(fr); System.out.println("r:" + r); pw.close(); m_logger.info("executeScript:" + sw); System.out.println("executeScript:" + sw); return null; }
From source file:com.adobe.acs.tools.test_page_generator.impl.TestPageGeneratorServlet.java
private Object eval(final ScriptEngine scriptEngine, final Object value) { if (scriptEngine == null) { log.warn("ScriptEngine is null; cannot evaluate"); return value; } else if (value instanceof String[]) { final List<String> scripts = new ArrayList<String>(); final String[] values = (String[]) value; for (final String val : values) { scripts.add(String.valueOf(this.eval(scriptEngine, val))); }/*ww w .j av a2s . c om*/ return scripts.toArray(new String[scripts.size()]); } else if (!(value instanceof String)) { return value; } final String stringValue = StringUtils.stripToEmpty((String) value); String script; if (StringUtils.startsWith(stringValue, "{{") && StringUtils.endsWith(stringValue, "}}")) { script = StringUtils.removeStart(stringValue, "{{"); script = StringUtils.removeEnd(script, "}}"); script = StringUtils.stripToEmpty(script); try { return scriptEngine.eval(script); } catch (ScriptException e) { log.error("Could not evaluation the test page property ecma [ {} ]", script); } } return value; }