List of usage examples for javax.script ScriptEngine put
public void put(String key, Object value);
From source file:io.stallion.tools.ScriptExecBase.java
public void executeJavascript(String source, URL url, String scriptPath, String folder, List<String> args, String plugin) throws Exception { ScriptEngine scriptEngine = null; if (plugin.equals("js") || plugin.equals("stallion")) { JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine("main.js"); if (pluginEngine != null) { scriptEngine = pluginEngine.getScriptEngine(); }//from w w w. j ava2 s . c o m } else if (!empty(plugin)) { JsPluginEngine pluginEngine = PluginRegistry.instance().getEngine(plugin); if (pluginEngine != null) { scriptEngine = pluginEngine.getScriptEngine(); } } if (scriptEngine == null) { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = scriptEngineManager.getEngineByName("nashorn"); scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/jvm-npm.js"), UTF8)); scriptEngine.eval(IOUtils.toString(getClass().getResource("/jslib/stallion_shared.js"), UTF8)); String nodePath = folder + "/node_modules"; scriptEngine.eval("require.NODE_PATH = \"" + nodePath + "\""); scriptEngine.put("myContext", new SandboxedContext(plugin, Sandbox.allPermissions(), new JsPluginSettings())); } if (true || newCommandOptions().isDevMode()) { Scanner in = new Scanner(System.in); while (true) { source = IOUtils.toString(url, UTF8); try { scriptEngine.eval("load(" + JSON.stringify(map(val("script", source), val("name", url.toString()))) + ");"); //scriptEngine.eval(IOUtils.) } catch (Exception e) { ExceptionUtils.printRootCauseStackTrace(e); } finally { } System.out.println("Hit enter to re-run the script. Type quit and hit enter to stop."); String line = in.nextLine().trim(); if (empty(line)) { continue; } else { break; } } } else { scriptEngine.eval(source); } }
From source file:org.jwebsocket.plugins.scripting.app.BaseScriptApp.java
/** * Constructor//from w ww. j ava 2 s . co m * * @param aPlugIn The ScriptingPlugIn reference that allows to script * applications to get access to the TokenServer instance. * @param aAppName The application name (unique value) * @param aAppPath The application directory path * @param aScriptApp The scripting engine that runs the application * @param aClassLoader */ public BaseScriptApp(ScriptingPlugIn aPlugIn, String aAppName, String aAppPath, ScriptEngine aScriptApp, LocalLoader aClassLoader) { mPlugIn = aPlugIn; mAppName = aAppName; mAppPath = aAppPath; mScriptApp = aScriptApp; mLogger = new ScriptAppLogger(mLog, aAppName); mServerClient = new ServerClient(this); mClassLoader = aClassLoader; mNodeId = JWebSocketConfig.getConfig().getNodeId(); // registering global "AppUtils" resource aScriptApp.put("AppUtils", this); mJWSHome = JWebSocketConfig.getJWebSocketHome(); }
From source file:org.wandora.modules.ModuleManager.java
/** * Parses a single param element and returns its value. Handles all the * different cases of how a param elements value can be determined. * //from w w w .ja va 2s.co m * @param e The xml param element. * @return The value of the parameter. */ public Object parseXMLParamElement(Element e) throws ReflectiveOperationException, IllegalArgumentException, ScriptException { String instance = e.getAttribute("instance"); if (instance != null && instance.length() > 0) { Class cls = Class.forName(instance); HashMap<String, Object> params = parseXMLOptionsElement(e); if (!params.isEmpty()) { Collection<Object> constructorParams = params.values(); Constructor[] cs = cls.getConstructors(); ConstructorLoop: for (int i = 0; i < cs.length; i++) { Constructor c = cs[i]; Class[] paramTypes = c.getParameterTypes(); if (paramTypes.length != constructorParams.size()) continue; int j = -1; for (Object o : constructorParams) { j++; if (o == null) { if (!paramTypes[j].isPrimitive()) continue; else continue ConstructorLoop; } if (paramTypes[j].isPrimitive()) { if (paramTypes[j] == int.class) { if (o.getClass() != Integer.class) continue ConstructorLoop; } else if (paramTypes[j] == long.class) { if (o.getClass() != Long.class) continue ConstructorLoop; } else if (paramTypes[j] == double.class) { if (o.getClass() != Double.class) continue ConstructorLoop; } else if (paramTypes[j] == float.class) { if (o.getClass() != Float.class) continue ConstructorLoop; } else if (paramTypes[j] == byte.class) { if (o.getClass() != Byte.class) continue ConstructorLoop; } else continue ConstructorLoop; //did we forget some primitive type? } else if (!o.getClass().isAssignableFrom(paramTypes[j])) continue ConstructorLoop; } return c.newInstance(constructorParams.toArray()); } throw new NoSuchMethodException( "Couldn't find a constructor that matches parameters parsed from XML."); } else { return cls.newInstance(); } } String clas = e.getAttribute("class"); if (clas != null && clas.length() > 0) { Class cls = Class.forName(clas); return cls; } if (e.hasAttribute("null")) return null; if (e.hasAttribute("script")) { String engine = e.getAttribute("script"); if (engine.length() == 0 || engine.equalsIgnoreCase("default")) engine = ScriptManager.getDefaultScriptEngine(); ScriptManager scriptManager = new ScriptManager(); ScriptEngine scriptEngine = scriptManager.getScriptEngine(engine); scriptEngine.put("moduleManager", this); scriptEngine.put("element", e); try { String script = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim(); return scriptManager.executeScript(script, scriptEngine); } catch (XPathExpressionException xpee) { throw new RuntimeException(xpee); } } if (e.hasAttribute("module")) { String moduleName = e.getAttribute("module").trim(); return new ModuleDelegate(this, moduleName); } try { String value = ((String) xpath.evaluate("text()", e, XPathConstants.STRING)).trim(); return replaceVariables(value, variables); } catch (XPathExpressionException xpee) { throw new RuntimeException(xpee); } }
From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java
/** * Start monitoring (as a thread) return when stopped */// ww w .j a va 2 s .c o m @Override public void run() { try { while (!stopping) { long currentRun = new Date().getTime(); logger.debug("Checking interval for {} at {}", name, currentRun); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); if (lastRun == null || lastRun + interval < currentRun) { logger.debug("Running interval for {} at {}", name, currentRun); // Run Monitors for (String monitorUrlHolderKey : monitorUrlHolders.keySet()) { MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlHolderKey); if (isFailed(monitorUrlHolder)) { logger.debug("Reinitialising monitors as they are not connected"); initialiseMonitorUrl(monitorUrlHolder.getUrl(), monitorsConfiguration); } else { logger.debug("Executing Monitors"); Map<String, Object> results = new HashMap<String, Object>(); for (Monitor monitor : monitorUrlHolder.getMonitors()) { try { results.put(monitor.getName(), monitor.getReading()); } catch (ReadingFailedException e) { results.put(monitor.getName(), e); logger.error("{}", e); } } for (String key : results.keySet()) { scriptEngine.put(key, results.get(key)); } } } for (String expression : expressions) { try { Object output = scriptEngine.eval(expression); outputLogger.info("{}", output); } catch (ScriptException e) { logger.warn("Script Error {}", e); } } // Run and output expressions lastRun = currentRun; } Thread.sleep(4000); } } catch (InterruptedException e) { logger.info("Interrupted", e); } catch (MalformedObjectNameException e) { logger.error("{}", e); throw new RuntimeException(e); } catch (MalformedURLException e) { logger.error("{}", e); throw new RuntimeException(e); } finally { // Tidy up all monitors / expressions IF possible alive = false; } }
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 List<PayTempKalkulasi> getAllDataCalculatedPayment(Date startPeriodDate, Date endPeriodDate, Date createdOn, String createdBy) throws Exception { //initial/*from w ww. jav a2 s.c o m*/ PaySalaryComponent totalIncomeComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAKE_HOME_PAY); PaySalaryComponent taxComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAX); PaySalaryComponent ceilComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_CEIL); List<PayTempKalkulasi> datas = new ArrayList<PayTempKalkulasi>(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); Double basicSalary = null; Double workingDay = null; Double lessTime = null; Double moreTime = null; Double overTIme = null; Double totalDay = this.getDefaultWorkingDay(startPeriodDate, endPeriodDate); //total working day dari kelompok kerja DEFAULT(reguler) Double outPut = null; //Start calculation List<EmpData> totalEmployee = empDataDao.getAllDataNotTerminateAndJoinDateLowerThan(endPeriodDate); /*List<EmpData> totalEmployee = new ArrayList<EmpData>(); EmpData emp = empDataDao.getEntiyByPK((long)130); totalEmployee.add(emp);*/ for (EmpData empData : totalEmployee) { LOGGER.info( " ============= EMPLOYEE : " + empData.getBioData().getFirstName() + " ====================="); /** * Set initial variabel untuk masing2 karyawan, * yang akan dibutuhkan untuk perhitungan model komponen FORMULA (if any) * */ basicSalary = Double.parseDouble(empData.getBasicSalaryDecrypted()); PayTempOvertime payTempOvertime = payTempOvertimeDao.getEntityByEmpDataId(empData.getId()); overTIme = payTempOvertime != null ? payTempOvertime.getOvertime() : 0.0; PayTempAttendanceStatus payTempAttendanceStatus = payTempAttendanceStatusDao .getEntityByEmpDataId(empData.getId()); workingDay = payTempAttendanceStatus != null ? (double) payTempAttendanceStatus.getTotalAttendance() : 0.0; lessTime = ((workingDay > 0) && (workingDay < totalDay)) ? totalDay - workingDay : 0.0; moreTime = (workingDay > totalDay) ? workingDay - totalDay : 0.0; /** * Saat ini totalIncome masih temporary, karena belum dikurangi * pajak dan pembulatan CSR Sedangkan untuk final totalIncome (take * home pay) ada di proses(step) selanjutnya di batch proses, * silahkan lihat batch-config.xml */ BigDecimal totalIncome = new BigDecimal(0); List<PayComponentDataException> payComponentExceptions = payComponentDataExceptionDao .getAllByEmpId(empData.getId()); for (PayComponentDataException dataException : payComponentExceptions) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(dataException.getPaySalaryComponent()); kalkulasi.setFactor( this.getFactorBasedCategory(dataException.getPaySalaryComponent().getComponentCategory())); kalkulasi.setNominal(dataException.getNominal()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By ComponentDataException - " + dataException.getPaySalaryComponent().getName() + ", nominal : " + dataException.getNominal()); } int timeTmb = DateTimeUtil.getTotalDay(empData.getJoinDate(), createdOn); List<Long> componentIds = Lambda.extract(payComponentExceptions, Lambda.on(PayComponentDataException.class).getPaySalaryComponent().getId()); List<PaySalaryComponent> listPayComponetNotExcp = paySalaryComponentDao .getAllDataByEmpTypeIdAndActiveFromTmAndIdNotIn(empData.getEmployeeType().getId(), timeTmb, componentIds); if (null == Lambda.selectFirst(listPayComponetNotExcp, Lambda.having(Lambda.on(PaySalaryComponent.class).getModelComponent().getSpesific(), Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY))) && null == Lambda.selectFirst(payComponentExceptions, Lambda.having( Lambda.on(PayComponentDataException.class).getPaySalaryComponent() .getModelComponent().getSpesific(), Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY)))) { throw new BussinessException("global.error_user_does_not_have_basic_salary", empData.getNikWithFullName()); } for (PaySalaryComponent paySalaryComponent : listPayComponetNotExcp) { if (paySalaryComponent.getModelComponent().getSpesific().equals(HRMConstant.MODEL_COMP_UPLOAD)) { PayTempUploadData payUpload = this.payTempUploadDataDao .getEntityByEmpIdAndComponentId(empData.getId(), paySalaryComponent.getId()); if (payUpload != null) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(payUpload.getPaySalaryComponent()); kalkulasi.setFactor(this .getFactorBasedCategory(payUpload.getPaySalaryComponent().getComponentCategory())); BigDecimal nominal = new BigDecimal(payUpload.getNominalValue()); kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Upload - " + payUpload.getPaySalaryComponent().getName() + ", nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_BASIC_SALARY)) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(empData.getBasicSalaryDecrypted()); if ((timeTmb / 30) < 1) { //jika TMB belum memenuhi satu bulan, jadi basic salary dibagi pro-rate nominal = nominal.divide(new BigDecimal(timeTmb), RoundingMode.UP); } kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Basic Salary " + (((timeTmb / 30) < 1) ? "Not Full" : "Full") + ", nominal : " + nominal); } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_LOAN)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak LoanNewType loanType = loanNewTypeDao .getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (loanType == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } List<LoanNewApplicationInstallment> installments = loanNewApplicationInstallmentDao .getAllDataDisbursedByEmpDataIdAndLoanTypeIdAndPeriodDate(empData.getId(), loanType.getId(), startPeriodDate, endPeriodDate); for (LoanNewApplicationInstallment installment : installments) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(installment.getTotalPayment()); nominal = nominal.setScale(0, RoundingMode.UP); kalkulasi.setNominal(nominal); //set detail loan int termin = installment.getLoanNewApplication().getTermin(); long cicilanKe = termin - installment.getNumOfInstallment(); kalkulasi.setDetail(cicilanKe + "/" + termin); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Loan - " + paySalaryComponent.getName() + ", nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_REIMBURSEMENT)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak RmbsType rmbsType = rmbsTypeDao.getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (rmbsType == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } List<RmbsApplication> reimbursments = rmbsApplicationDao .getAllDataDisbursedByEmpDataIdAndRmbsTypeIdAndPeriodDate(empData.getId(), rmbsType.getId(), startPeriodDate, endPeriodDate); for (RmbsApplication reimbursment : reimbursments) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); kalkulasi.setNominal(reimbursment.getNominal()); //set detail reimbursement kalkulasi.setDetail(reimbursment.getCode()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Reimbursment, nominal : " + reimbursment.getNominal()); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_FORMULA)) { String formulaOne = paySalaryComponent.getFormula(); if (formulaOne != null) { jsEngine.put("bS", basicSalary); jsEngine.put("wD", workingDay); jsEngine.put("lT", lessTime); jsEngine.put("mT", moreTime); jsEngine.put("oT", overTIme); jsEngine.put("tD", totalDay); outPut = (Double) jsEngine.eval(formulaOne); PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(outPut); kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Formula, nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_BENEFIT_TABLE)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak BenefitGroup benefitGroup = benefitGroupDao .getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (benefitGroup == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } //cek apakah tunjangan yg didapatkan sesuai dengan hak dari golonganJabatan karyawan BenefitGroupRate benefitGroupRate = benefitGroupRateDao .getEntityByBenefitGroupIdAndGolJabatanId(benefitGroup.getId(), empData.getGolonganJabatan().getId()); if (benefitGroupRate != null) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); //nominal untuk benefit dikali nilai dari measurement BigDecimal nominal = new BigDecimal(benefitGroupRate.getNominal()).multiply(this .getMultiplierFromMeasurement(benefitGroupRate.getBenefitGroup().getMeasurement())); kalkulasi.setNominal(nominal); //set detail benefit kalkulasi.setDetail(benefitGroupRate.getGolonganJabatan().getCode()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Benefit - " + paySalaryComponent.getName() + ", nominal : " + nominal); } } } //create totalIncome Kalkulasi, hasil penjumlahan nominal dari semua component di atas PayTempKalkulasi totalIncomeKalkulasi = new PayTempKalkulasi(); totalIncomeKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); totalIncomeKalkulasi.setEmpData(empData); totalIncomeKalkulasi.setPaySalaryComponent(totalIncomeComponent); totalIncomeKalkulasi .setFactor(this.getFactorBasedCategory(totalIncomeComponent.getComponentCategory())); totalIncomeKalkulasi.setNominal(totalIncome); totalIncomeKalkulasi.setCreatedBy(createdBy); totalIncomeKalkulasi.setCreatedOn(createdOn); datas.add(totalIncomeKalkulasi); //create initial tax Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya PayTempKalkulasi taxKalkulasi = new PayTempKalkulasi(); taxKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); taxKalkulasi.setEmpData(empData); taxKalkulasi.setPaySalaryComponent(taxComponent); taxKalkulasi.setFactor(this.getFactorBasedCategory(taxComponent.getComponentCategory())); taxKalkulasi.setNominal(new BigDecimal(0)); taxKalkulasi.setCreatedBy(createdBy); taxKalkulasi.setCreatedOn(createdOn); datas.add(taxKalkulasi); //create initial ceil Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya PayTempKalkulasi ceilKalkulasi = new PayTempKalkulasi(); ceilKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); ceilKalkulasi.setEmpData(empData); ceilKalkulasi.setPaySalaryComponent(ceilComponent); ceilKalkulasi.setFactor(this.getFactorBasedCategory(ceilComponent.getComponentCategory())); ceilKalkulasi.setNominal(new BigDecimal(0)); ceilKalkulasi.setCreatedBy(createdBy); ceilKalkulasi.setCreatedOn(createdOn); datas.add(ceilKalkulasi); } return datas; }