public Map<String, Object> eval( Set<String> allowedClasses, Map<String, Object> inputObjects, Set<String> outputNames, String script) throws ScriptingException { if (allowedClasses != null) { throw new ExecutionException("Constrained execution not supported for BeanShell"); } try { Interpreter interpreter = new Interpreter(); for (Map.Entry<String, Object> entry : inputObjects.entrySet()) { interpreter.set(entry.getKey(), entry.getValue()); } interpreter.eval(script); if (outputNames == null) { return null; } Map<String, Object> outputObjects = new HashMap<String, Object>(); for (String outputName : outputNames) { outputObjects.put(outputName, interpreter.get(outputName)); } return outputObjects; } catch (Exception e) { throw new ScriptingException(e.getMessage(), e); } }
/** * Runs a BeanShell script. Errors are passed to the caller. * * <p>If the <code>in</code> parameter is non-null, the script is read from that stream; otherwise * it is read from the file identified by <code>path</code> . * * <p>The <code>scriptPath</code> BeanShell variable is set to the path name of the script. * * @param path The script file's VFS path. * @param in The reader to read the script from, or <code>null</code> . * @param namespace The namespace to run the script in. * @exception Exception instances are thrown when various BeanShell errors occur * @since jEdit 4.2pre5 */ public void _runScript(String path, Reader in, NameSpace namespace) throws Exception { log.info("Running script " + path); Interpreter interp = createInterpreter(namespace); try { if (in == null) { in = res.getResourceAsReader(path); } setupDefaultVariables(namespace); interp.set("scriptPath", path); running = true; interp.eval(in, namespace, path); } catch (Exception e) { unwrapException(e); } finally { running = false; try { // no need to do this for macros! if (namespace == global) { resetDefaultVariables(namespace); interp.unset("scriptPath"); } } catch (EvalError e) { // do nothing } } } // }}}
public static void main(String[] args) throws EvalError { String cf = "\"sdfsdfsdf【\"+@UUID()+\"】SDFSDFSDF\""; CFormExp exp = new CFormExp("3", new HashMap()); String ret = exp.eval_UUID(cf); System.out.println(ret); Interpreter i = new Interpreter(); try { cf = i.eval(ret) + ""; } catch (EvalError e) { e.printStackTrace(); } System.out.println("计算结果:" + cf); // // // // Interpreter i = new Interpreter(); // i.set("DEPTNAME", new String("SSS")); // Object x = i.eval("DEPTNAME.eq(\"SSS\")"); // System.out.println(x); // Interpreter i = new Interpreter(); // i.set("A", 100); // i.set("B", 200); // i.set("C", 150); // System.out.println(i.eval("(A<B) && (A>C)")); // String v = exp.eval_SYSDT("@SYSDT(\"\")+@SYSDT(\"\")"); // System.out.println(v); }
/** * Pokrece pilot-beanshell skripte za ubacivanje podataka iz stranih baza Potrebno je prijaviti * reportext sa NASLOVOM kao naziv klase za knjizenje, te aplikacijum sisfun npr. IME=1, * NASLOV=hr.restart.robno.frmKnjRobno, URL=robnoloader.sql, APP=sisfun i sve skripte sa tim * naslovom ce se izvrsiti prije validacija() metode u NASLOV klasi sortirane by IME (pazi string * sort!) * * @return */ private boolean runPreloader() { try { String cname = this.getClass().getName(); // executeReport(java.net.URL rep, String title, Window owner) QueryDataSet preloaders = Reportext.getDataModule() .getFilteredDataSet( Condition.whereAllEqual( new String[] {"NASLOV", "APP"}, new String[] {cname, "sisfun"})); preloaders.open(); if (preloaders.getRowCount() == 0) return true; preloaders.setSort(new SortDescriptor("IME")); for (preloaders.first(); preloaders.inBounds(); preloaders.next()) { // // raPilot.executeReport(Aus.findFileAnywhere(preloaders.getString("URL")).toURL(),cname, // this ); Interpreter interpreter = new Interpreter(); Object ret = interpreter.eval( FileHandler.readFile( Aus.findFileAnywhere(preloaders.getString("URL")).getAbsolutePath())); return ((Boolean) ret).booleanValue(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; }
private static void endInterpreter(String contextId) throws EvalError { Interpreter i = interpreters.get(contextId); if (i == null) return; i.eval("clear();"); // can't hurt to tell bsh to clean up internally interpreters.remove(contextId); // now wait for GC Log.log("Destroyed context: " + contextId + " (" + i + ")"); }
/** * Execute Script Loads environment and saves result * * @return null or Exception */ public Exception execute() { m_result = null; if (m_variable == null || m_variable.length() == 0 || m_script == null || m_script.length() == 0) { IllegalArgumentException e = new IllegalArgumentException("No variable/script"); log.config(e.toString()); return e; } Interpreter i = new Interpreter(); loadEnvironment(i); try { log.config(m_script); i.eval(m_script); } catch (Exception e) { log.config(e.toString()); return e; } try { m_result = i.get(m_variable); log.config("Result (" + m_result.getClass().getName() + ") " + m_result); } catch (Exception e) { log.config("Result - " + e); if (e instanceof NullPointerException) e = new IllegalArgumentException("Result Variable not found - " + m_variable); return e; } return null; } // execute
/** * 计算公式 * * @param cf * @return * @throws Exception */ public String eval(String cf) { if (StringUtil.isNotEmpty(cf)) { cf = StringUtil.decodeChars(cf, "@,>,<,+,-,?,(,), ,.,:,\",'"); } cf = eval_VALUE(cf); // 1.匹配@VALUE公式 cf = eval_CONTEXT(cf); // 1.匹配@CONTEXT公式 cf = eval_PARSENUMBER(cf); // 2.匹配@PARSENUMBER();公式 cf = eval_SYSDT(cf); // 3.匹配@SYSDT公式 cf = eval_GROUPNAME(cf); // 4.匹配@GROUPNAME公式 cf = eval_GROUPSHORTNAME(cf); // 5.匹配@GROUPSHORTNAME公式 cf = eval_HTTPSESSION(cf); // 6.匹配@HTTPSESSION公式 cf = eval_USERLOGINNAME(cf); // 7.匹配@USERLOGINNAME公式 cf = eval_USERLOGINID(cf); // 8.匹配@USERLOGINID公式 cf = eval_USERCNAME(cf); // 9.匹配@USERCNAME公式 cf = eval_SQL(cf); // 10.匹配@SQL公式 cf = eval_UUID(cf); // 11.匹配@UUID公式 cf = eval_INVOKE(cf); // 11.匹配@UUID公式 cf = eval_IF(cf); // 12.匹配@IF公式 Interpreter i = new Interpreter(); try { cf = i.eval(cf) + ""; } catch (EvalError e) { e.printStackTrace(); String msg = e.getMessage(); msg = StringUtil.formatHTML(msg); return "%ERROR%"; } return cf; }
/** * 条件判断 @IF(表单变量?"":""); aaa && bbb || ccc * * @param cf * @return */ public String eval_IF(String cf) { // "123"+@IF((A>100 && B<100)?@UUID():@VALUE()); String regex = "@IF\\(.*\\)"; // 匹配@IF公式 Pattern p = Pattern.compile(regex); Matcher mt = p.matcher(cf); while (mt.find()) { String group = mt.group(); String condition = group.substring(group.indexOf("(") + 1, group.indexOf("?")); String v1 = group.substring(group.indexOf("?") + 1, group.indexOf(":")); String v2 = group.substring(group.indexOf(":") + 1, group.lastIndexOf(")")); Interpreter i = new Interpreter(); String v = "\"\""; try { initEvalContext(i); Boolean ret = (Boolean) i.eval(condition); if (ret == true) { v = v1; } else { v = v2; } mt = p.matcher(cf); } catch (Exception ex) { // ex.printStackTrace(); } cf = mt.replaceFirst(v); } return cf; }
private void source(Interpreter interpreter) { for (IConfigurationElement config : getExtensionInfo("org.jactr.tools.shell.commands", "source")) { String url = config.getAttribute("url"); String resource = config.getAttribute("resource"); URL actualURL = null; if (resource != null) actualURL = getClass().getClassLoader().getResource(resource); else if (url != null) try { actualURL = new URL(url); } catch (Exception e) { if (LOGGER.isWarnEnabled()) LOGGER.warn(url + " is not a valid url ", e); } if (actualURL != null) try { interpreter.set("tmpURL", actualURL); interpreter.eval("source(tmpURL)"); interpreter.unset("tmpURL"); } catch (EvalError e) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Could not source " + url + " ", e); } } }
@Override public String getUrlToLoad(int x, int y, int zoom) { if (zoom > maxZoom) return null; SQLiteConnection db = getDatabase(); if (db == null || db.isReadOnly() || urlTemplate == null) { return null; } if (TileSourceManager.RULE_BEANSHELL.equalsIgnoreCase(rule)) { try { if (bshInterpreter == null) { bshInterpreter = new Interpreter(); bshInterpreter.eval(urlTemplate); } return (String) bshInterpreter.eval("getTileUrl(" + zoom + "," + x + "," + y + ");"); } catch (bsh.EvalError e) { LOG.debug("getUrlToLoad Error" + e.getMessage()); AccessibleToast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show(); LOG.error(e.getMessage(), e); return null; } } else { return MessageFormat.format( urlTemplate, zoom + "", x + "", y + ""); // $NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ } }
public String transform(String message) { String rv = message; try { log.debug("in=" + message); // decode the message org.jengine.tools.hl7.Message msg = org.jengine.tools.hl7.Message.read(new java.io.StringReader(message)); // pass the decoded message to beanshell interpreter.eval("org.jengine.tools.hl7.Message message"); interpreter.set("message", msg); // pass the logging category to beanshell interpreter.eval("org.apache.log4j.Category log"); interpreter.set("log", log); // call the script interpreter.eval(script); // encode the possibly modified message java.io.StringWriter sw = new java.io.StringWriter(); msg.write(sw); rv = sw.toString(); log.debug("out=" + rv); } catch (Exception e) { log.error("Problem processing transformation", e); } return rv; }
private void setCommonVars(Interpreter i, BRoom room) throws EvalError { i.getNameSpace().clear(); BRoomBuilder builder = new BRoomBuilder(room); i.set("room", builder.room()); i.set("builder", builder); i.eval("void addLayers(String[][] s){ builder.addLayers(s); }"); i.eval( "void setDoorDestination(String doorIndex, String destRoomId, String destDoorIndex){ room.setDoorDestination(doorIndex,destRoomId,destDoorIndex); }"); }
public boolean populateRoom(BResourceLocator script, BRoom room) throws EvalError, IOException { Interpreter i = interpreter(); setCommonVars(i, room); Reader r = reader(script); if (r == null) { return false; } i.eval(r); return true; }
public void run() { Element config = getPersist(); try { bsh.set("qbean", this); bsh.set("log", getLog()); bsh.set("cfg", getConfiguration()); bsh.eval(config.getText()); String source = config.getAttributeValue("source"); if (source != null) bsh.source(source); } catch (Throwable e) { getLog().warn(e); } }
private Number calcYears(Integer age, String script) { if (StringUtils.isEmpty(script)) { return Double.NaN; } Interpreter interpreter = new Interpreter(); try { interpreter.set("age", new Integer(30)); Number years = (Number) interpreter.eval("41 - age"); return years.intValue(); } catch (EvalError e) { throw new RuntimeException(e); } }
/** * execute * * @param env OpenKM API internal environment data. * @param params Action configured parameters. */ private void execute(HashMap<String, Object> env, Object... params) { String script = AutomationUtils.getString(0, params); NodeBase node = AutomationUtils.getNode(env); String uuid = AutomationUtils.getUuid(env); File file = AutomationUtils.getFile(env); try { Interpreter i = new Interpreter(); i.set("node", node); i.set("uuid", uuid); i.set("file", file); if (env.get(AutomationUtils.NODE_UUID) != null) { i.set(AutomationUtils.NODE_UUID, env.get(AutomationUtils.NODE_UUID)); } if (env.get(AutomationUtils.NODE_PATH) != null) { i.set(AutomationUtils.NODE_PATH, env.get(AutomationUtils.NODE_PATH)); } if (env.get(AutomationUtils.PROPERTY_GROUP_NAME) != null) { i.set(AutomationUtils.PROPERTY_GROUP_NAME, env.get(AutomationUtils.PROPERTY_GROUP_NAME)); } if (env.get(AutomationUtils.PROPERTY_GROUP_PROPERTIES) != null) { i.set( AutomationUtils.PROPERTY_GROUP_PROPERTIES, env.get(AutomationUtils.PROPERTY_GROUP_PROPERTIES)); } i.eval(script); } catch (Exception e) { log.error(e.getMessage(), e); } }
private static void runStartupScript(File initsh) throws EvalError, URISyntaxException, FileNotFoundException, IOException { Interpreter bsh = new Interpreter(); String initScript = new String( Util.catFile( ClassLoader.getSystemResource("eunomia/util/scripts/commands.esh").toURI())); bsh.eval(initScript); if (initsh.exists()) { bsh.source(initsh.toString()); } }
public void set_variable(String s, Object o) { try { main_interpreter.set(s, o); } catch (EvalError evalError) { evalError.printStackTrace(); } }
/** * DOCUMENT ME! * * @param callstack DOCUMENT ME! * @param interpreter DOCUMENT ME! * @param parameterNode DOCUMENT ME! * @return DOCUMENT ME! * @throws EvalError DOCUMENT ME! */ public Object filter(CallStack callstack, Interpreter interpreter, Node parameterNode) throws EvalError { int col = getColumn(); if (parameterNode instanceof BSHArguments) { Object[] keys = ((BSHArguments) parameterNode).getArguments(callstack, interpreter); for (int i = 0; i < keys.length; i++) { keys[i] = Primitive.unwrap(keys[i]); } Key key = null; if ((keys.length == 1) && (keys[0] == Dataset.ANY)) { key = Dataset.ANY; } else { key = new Key(keys); } Object value2 = new FilteredIndexField(this.indexView, key, col); interpreter.getRoot().setValue2(value2); return value2; } return null; }
public String[][] exec(String[] befehle) { String[][] antworten = new String[befehle.length][1]; Object aktObj; for (int i = 0; i < befehle.length; i++) { try { aktObj = interpreter.eval(befehle[i]); if (aktObj != null) antworten[i][0] = aktObj.toString(); else antworten[i][0] = "null"; } catch (EvalError e) { System.err.println(e.getMessage()); antworten[i][0] = "ERROR"; } if (verbose) { assert !quiet; System.out.println("# " + i + ": " + befehle[i]); for (int j = 0; j < antworten[i].length; j++) { System.out.println("@ " + antworten[i][j]); } } else if (!quiet) for (int j = 0; j < antworten[i].length; j++) { System.out.print("#"); } } return antworten; }
/** * Set Environment for Interpreter * * @param i Interpreter */ private void loadEnvironment(Interpreter i) { if (m_ctx == null) return; Iterator<String> it = m_ctx.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object value = m_ctx.get(key); try { if (value instanceof Boolean) i.set(key, ((Boolean) value).booleanValue()); else if (value instanceof Integer) i.set(key, ((Integer) value).intValue()); else if (value instanceof Double) i.set(key, ((Double) value).doubleValue()); else i.set(key, value); } catch (EvalError ee) { log.log(Level.SEVERE, "", ee); } } } // setEnvironment
public Object get(String s) { try { return main_interpreter.get(s); } catch (EvalError evalError) { evalError.printStackTrace(); } return null; }
/** * Faz a evaluation dos dados statements contidos na string, permitindo a utilizacão da informacão * do dado contexto. */ public static Object eval(String statements, Map context) { bsh.Interpreter bsh = new bsh.Interpreter(); try { if (context != null) { Iterator entries = context.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); bsh.set((String) entry.getKey(), entry.getValue()); } } return bsh.eval(statements); } catch (EvalError e) { log.error(e.getMessage()); return null; } }
public void initService() { bsh = new Interpreter(); BshClassManager bcm = bsh.getClassManager(); try { bcm.setClassPath(getServer().getLoader().getURLs()); } catch (UtilEvalError e) { e.printStackTrace(); } bcm.setClassLoader(getServer().getLoader()); }
public Object evaluate(String s) { System.out.println(s); evaluations += s; try { return main_interpreter.eval(s); } catch (EvalError evalError) { evalError.printStackTrace(); } return null; }
synchronized void createInterpreter() { // create interpreter just-in-time if (interpreter == null) { interpreter = new Interpreter(); try { interpreter.set("bsh_prot", this); } catch (EvalError evalError) { } } }
@Override public void initAndValidate() { interpreter = new Interpreter(); NamedFunction.evalFunctionInputs(interpreter, functionInputs.get()); String script = valueInput.get(); try { interpreter.eval(script); } catch (EvalError e) { throw new RuntimeException(e); } }
Object evalScript( String script, StringBuffer scriptOutput, boolean captureOutErr, HttpServletRequest request, HttpServletResponse response) throws EvalError { // Create a PrintStream to capture output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(baos); // Create an interpreter instance with a null inputstream, // the capture out/err stream, non-interactive Interpreter bsh = new Interpreter(null, pout, pout, false); // set up interpreter bsh.set("bsh.httpServletRequest", request); bsh.set("bsh.httpServletResponse", response); // Eval the text, gathering the return value or any error. Object result = null; String error = null; PrintStream sout = System.out; PrintStream serr = System.err; if (captureOutErr) { System.setOut(pout); System.setErr(pout); } try { // Eval the user text result = bsh.eval(script); } finally { if (captureOutErr) { System.setOut(sout); System.setErr(serr); } } pout.flush(); scriptOutput.append(baos.toString()); return result; }
/** * 得到一个方法 * * @param methodName 方法名 * @param paraTypes 参数类型 * @return 方法实现 */ private BshMethod getMethod(String methodName, Class[] paraTypes) { try { BshMethod bm = interpreter.getNameSpace().getMethod(methodName, paraTypes); if (bm != null) { return bm; } } catch (UtilEvalError utilEvalError) { L.e(utilEvalError); } return null; }
private void importCommands(Interpreter interpreter) { for (IConfigurationElement config : getExtensionInfo("org.jactr.tools.shell.commands", "package")) { String packageName = config.getAttribute("name"); try { interpreter.eval("importCommands(\"" + packageName + "\")"); } catch (EvalError e) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Could not import commands from " + packageName + " ", e); } } }