@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$ } }
private ScriptErrorRaisedException processBshException(bsh.EvalError e, String script) { LogUtils.DEBUG("Beanshell error RAW message " + e.getMessage()); String message = e.getMessage(); int usefulInfoIndex = message.lastIndexOf("\' :"); int lineNum = e.getErrorLineNumber(); raiseEditor(lineNum); // String stackTrace = te.getScriptStackTrace(); // never seems to have any info?? if (usefulInfoIndex > -1) { message = message.substring(usefulInfoIndex + 2); } if (e instanceof bsh.TargetError) { LogUtils.DEBUG("got instance of TargetError"); if (usefulInfoIndex == -1) { message = ((bsh.TargetError) e).getTarget().getMessage(); } String wrappedException = ""; String full = e.toString(); int index = full.indexOf("Target exception:"); if (index > -1) { String toParse = full.substring(index); LogUtils.DEBUG("About to parse " + toParse); StringTokenizer tokenizer = new StringTokenizer(full.substring(index), ":"); if (tokenizer.countTokens() > 2) { LogUtils.DEBUG("First token = " + (String) tokenizer.nextElement()); wrappedException = (String) tokenizer.nextElement(); LogUtils.DEBUG("wrapped exception = = " + wrappedException); } } ScriptExceptionRaisedException se = new ScriptExceptionRaisedException(message); se.lineNum = lineNum; se.scriptName = script; se.exceptionType = wrappedException; se.language = "BeanShell"; LogUtils.DEBUG("UnCaught Exception error: "); LogUtils.DEBUG("\tscript: " + script); LogUtils.DEBUG("\tline: " + lineNum); LogUtils.DEBUG("\twrapped exception: " + wrappedException); LogUtils.DEBUG("\tmessage: " + message); return se; } else { LogUtils.DEBUG("Error or ParseError Exception error: "); LogUtils.DEBUG("\tscript: " + script); LogUtils.DEBUG("\tline: " + lineNum); LogUtils.DEBUG("\tmessage: " + message); return new ScriptErrorRaisedException(message, null, script, "BeanShell", lineNum); } }
/** * 计算公式 * * @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; }
/** * Sets variable in scripter context. * * @param name * @param value */ public void setVariable(String name, Object value) { try { this.beanShellInterpreter.set(name, value); } catch (EvalError e) { throw new ScriptException("Cannot set variable in scripter: " + e.getMessage(), e); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String formula = request.getParameter("formula"); if (formula == null) return; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); try { Object resultado = getNegocio().executarFormula(formula); out.println("<b><font color='blue'>Fórmula:</font></b>" + "<b>" + formula + "</b>" + "<br>"); out.println( "<b><font color='blue'>Resultado:</font></b>" + "<b>" + resultado + "</b>" + "<br>"); out.println( "<b><font color='black'>Execução:</font></b>" + "<b>" + sdf.format(new Date()) + "</b>" + "<br>"); } catch (EvalError e) { out.println( "<b><font color='red'>Erro ao executar fórmula:</font></b>" + "<b>" + e.getMessage() + "</b>" + "<br>"); e.printStackTrace(); } }
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; }
/** * Constructor - initializes context used in engine. * * @param context */ public BeanShellScriptEngine(Map context) { super(context); this.beanShellInterpreter.getNameSpace().importCommands("org.webharvest.runtime.scripting"); try { this.beanShellInterpreter.set(CONTEXT_VARIABLE_NAME, this.context); } catch (EvalError e) { throw new ScriptException("Cannot set Web-Harvest context in scripter: " + e.getMessage(), e); } }
@Test public void testExecuteThrowsEvalError1() throws Throwable { Map<Object, Comparable<String>> arguments = new HashMap(); try { new BSHMethod("testBSHMethod\rBshData", false).execute(arguments, "testBSHMethodResultName"); fail("Expected EvalError to be thrown"); } catch (EvalError ex) { assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod BshData;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod BshData;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals("(HashMap) arguments.size()", 0, arguments.size()); } }
/** * Evaluates specified expression or code block. * * @return value of evaluation or null if there is nothing. */ public Object eval(String expression) { pushAllVariablesFromContextToScriptEngine(); try { return this.beanShellInterpreter.eval(expression); } catch (EvalError e) { throw new ScriptException("Error during script execution: " + e.getMessage(), e); } }
@Test public void testExecuteThrowsEvalError() throws Throwable { Collection returnNames = new ArrayList(); try { new BSHMethod("testBSHMethod\rBshData", false).execute(arguments, returnNames); fail("Expected EvalError to be thrown"); } catch (EvalError ex) { assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod BshData;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod BshData;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals("(HashMap) arguments.size()", 0, arguments.size()); assertEquals("(ArrayList) returnNames.size()", 0, returnNames.size()); } }
@Test public void testInitInterpreterThrowsEvalError() throws Throwable { Element e = new Element("testBSHMethodName", Namespace.NO_NAMESPACE); e.addContent("testBSHMethod\rStr"); e.setAttributes(new ArrayList()); BSHMethod bshMethod = BSHMethod.createBshMethod(e); try { bshMethod.initInterpreter(arguments); fail("Expected EvalError to be thrown"); } catch (EvalError ex) { assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod Str;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals( "ex.getMessage()", "Sourced file: inline evaluation of: ``testBSHMethod Str;'' : Typed variable declaration : Class: testBSHMethod not found in namespace", ex.getMessage()); assertEquals("(HashMap) arguments.size()", 0, arguments.size()); } }
@Test public void testExecuteMethodThrowsEvalError() throws Throwable { BSHTransactionParticipant bSHGroupSelector = new BSHGroupSelector(); try { bSHGroupSelector.executeMethod( new BSHMethod("testBSHTransactionParticipantBshData", false), 100L, new CharConversionException(), new LogEvent(), "sh.evalOnly"); fail("Expected EvalError to be thrown"); } catch (EvalError ex) { assertEquals("ex.getMessage()", "Class or variable not found: sh.evalOnly", ex.getMessage()); assertEquals("ex.getMessage()", "Class or variable not found: sh.evalOnly", ex.getMessage()); } }
/** * 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 String[] exec(String befehl) { String[] antwort = new String[1]; Object aktObj; try { aktObj = interpreter.eval(befehl); if (aktObj != null) antwort[0] = aktObj.toString(); else antwort[0] = "null"; } catch (EvalError e) { System.err.println(e.getMessage()); antwort[0] = "ERROR"; } if (!quiet) System.out.print("#"); if (verbose) { assert !quiet; System.out.println(" " + befehl); System.out.println("@ " + antwort[0]); } return antwort; }
/** * documentStorageID and document reference for use in script name resolving * * @param aParams All parameters; pure, out params are undefined in sequence, i.e., the value has * to be ignored by the callee * @param aOutParamIndex Out indices * @param aOutParam Out parameters * @returns The value returned from the function being invoked * @throws IllegalArgumentException If there is no matching script name * @throws CannotConvertException If args do not match or cannot be converted the those of the * invokee * @throws InvocationTargetException If the running script throws an exception this information is * captured and rethrown as this exception type. */ public Object invoke( /*IN*/ Object[] aParams, /*OUT*/ short[][] aOutParamIndex, /*OUT*/ Object[][] aOutParam) throws ScriptFrameworkErrorException, InvocationTargetException { // Initialise the out parameters - not used at the moment aOutParamIndex[0] = new short[0]; aOutParam[0] = new Object[0]; ClassLoader cl = null; URL sourceUrl = null; try { cl = ClassLoaderFactory.getURLClassLoader(metaData); sourceUrl = metaData.getSourceURL(); } catch (java.net.MalformedURLException mfu) { // Framework error throw new ScriptFrameworkErrorException( mfu.getMessage(), null, metaData.getLanguageName(), metaData.getLanguage(), ScriptFrameworkErrorType.MALFORMED_URL); } catch (NoSuitableClassLoaderException nsc) { // Framework error throw new ScriptFrameworkErrorException( nsc.getMessage(), null, metaData.getLanguageName(), metaData.getLanguage(), ScriptFrameworkErrorType.UNKNOWN); } // Set class loader to be used for class files // and jar files Thread.currentThread().setContextClassLoader(cl); Interpreter interpreter = new Interpreter(); interpreter.getNameSpace().clear(); // Set class loader to be used by interpreter // to look for classes by source e.g. interpreter // will use this classloader to search classpath // for source file ( bla.java ) on import or reference interpreter.setClassLoader(cl); try { interpreter.set( "XSCRIPTCONTEXT", ScriptContext.createContext( m_xModel, m_xInvocContext, m_xContext, m_xMultiComponentFactory)); interpreter.set("ARGUMENTS", aParams); } catch (bsh.EvalError e) { // Framework error setting up context throw new ScriptFrameworkErrorException( e.getMessage(), null, metaData.getLanguageName(), metaData.getLanguage(), ScriptFrameworkErrorType.UNKNOWN); } try { String source = null; Object result = null; ScriptEditorForBeanShell editor = ScriptEditorForBeanShell.getEditor(sourceUrl); if (editor != null) { result = editor.execute(); if (result == null) { return new Any(new Type(), null); } return result; } metaData.loadSource(); source = metaData.getSource(); if (source == null || source.length() == 0) { throw new ScriptFrameworkErrorException( "Failed to read script", null, metaData.getLanguageName(), metaData.getLanguage(), ScriptFrameworkErrorType.NO_SUCH_SCRIPT); } result = interpreter.eval(source); if (result == null) { return new Any(new Type(), null); } return result; } catch (bsh.ParseException pe) { throw new InvocationTargetException( "Beanshell failed to parse " + metaData.getLanguageName(), null, processBshException(pe, metaData.getLanguageName())); } catch (bsh.TargetError te) { throw new InvocationTargetException( "Beanshell uncaught exception for " + metaData.getLanguageName(), null, processBshException(te, metaData.getLanguageName())); } catch (bsh.EvalError ex) { throw new InvocationTargetException( "Beanshell error for " + metaData.getLanguageName(), null, processBshException(ex, metaData.getLanguageName())); } catch (Exception e) { throw new ScriptFrameworkErrorException( "Failed to read script", null, metaData.getLanguageName(), metaData.getLanguage(), ScriptFrameworkErrorType.UNKNOWN); } }
@Override public boolean exec(MethodContext methodContext) throws MiniLangException { Interpreter bsh = new Interpreter(); bsh.setClassLoader(methodContext.getLoader()); try { // setup environment for (Map.Entry<String, Object> entry : methodContext.getEnvMap().entrySet()) { bsh.set(entry.getKey(), entry.getValue()); } // run external, from resource, first if resource specified if (UtilValidate.isNotEmpty(this.resource)) { InputStream is = methodContext.getLoader().getResourceAsStream(this.resource); if (is == null) { this.simpleMethod.addErrorMessage( methodContext, "Could not find bsh resource: " + this.resource); } else { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(is)); StringBuilder outSb = new StringBuilder(); String tempStr = null; while ((tempStr = reader.readLine()) != null) { outSb.append(tempStr); outSb.append('\n'); } Object resourceResult = bsh.eval(outSb.toString()); // if map is returned, copy values into env if ((resourceResult != null) && (resourceResult instanceof Map<?, ?>)) { methodContext.putAllEnv(UtilGenerics.<String, Object>checkMap(resourceResult)); } } catch (IOException e) { this.simpleMethod.addErrorMessage( methodContext, "IO error loading bsh resource: " + e.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { this.simpleMethod.addErrorMessage( methodContext, "IO error closing BufferedReader: " + e.getMessage()); } } } } } if (Debug.verboseOn()) Debug.logVerbose("Running inline BSH script: " + inline, module); // run inlined second to it can override the one from the property Object inlineResult = bsh.eval(inline); if (Debug.verboseOn()) Debug.logVerbose("Result of inline BSH script: " + inlineResult, module); // if map is returned, copy values into env if ((inlineResult != null) && (inlineResult instanceof Map<?, ?>)) { methodContext.putAllEnv(UtilGenerics.<String, Object>checkMap(inlineResult)); } } catch (EvalError e) { Debug.logWarning(e, "BeanShell execution caused an error", module); this.simpleMethod.addErrorMessage( methodContext, "BeanShell execution caused an error: " + e.getMessage()); } // always return true, error messages just go on the error list return true; }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { // A good request looks like /mljam/contextid/verb?name=varname // The extra path info includes the context id and verb String extra = req.getPathInfo(); // "/contextid/verb" if (extra == null || extra.equals("")) { throw new ClientProblemException( "Request requires a context id and verb in its extra path info"); } String[] parts = extra.split("/"); // { "", "contextid", "verb" } if (parts.length < 2) { throw new ClientProblemException( "Request requires a context id and verb in its extra path info"); } else if (parts.length < 3) { throw new ClientProblemException("Request requires a verb in its extra path info"); } String contextId = parts[1]; String verb = parts[2]; String method = req.getMethod(); if (method.equalsIgnoreCase("get")) { // We have three GET verbs: get, get-stdout, get-stderr. // These are all idempotent, while the POST verbs aren't. The get // verb accept a "name" query string parameter. The get verb returns // either XQuery to evaluate (indicated by x-marklogic/xquery content type) // or a raw binary (indicated by an application/binary-encoded content type). if (verb.equalsIgnoreCase("get")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The get verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); Object o = i.get(name); if (o instanceof byte[]) { sendBinaryResponse(res, (byte[]) o); } else if (o instanceof String) { sendStringResponse(res, (String) o); } else { sendXQueryResponse(res, o); } } else if (verb.equalsIgnoreCase("get-stdout")) { Interpreter i = getInterpreter(contextId); i.getOut().flush(); CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamout"); if (circ != null) { sendStringResponse(res, circ.toString()); circ.reset(); } else { throw new ServerProblemException("Could not fetch mljamout from interpreter context"); } } else if (verb.equalsIgnoreCase("get-stderr")) { Interpreter i = getInterpreter(contextId); i.getErr().flush(); CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamerr"); if (circ != null) { sendStringResponse(res, circ.toString()); circ.reset(); } else { throw new ServerProblemException("Could not fetch mljamerr from interpreter context"); } } else { throw new ClientProblemException("Unrecognized GET verb: " + verb); } } else if (method.equalsIgnoreCase("post")) { // We have six POST verbs: eval, unset, end, source, set-string, and set-binary. // These are POST verbs because they aren't idempotent. // The set-string, set-binary, unset, and source verbs accept a "name" // query string parameter. The set-string and set-binary verbs accept // a value in their post body. The eval verb accepts code in its post body. if (verb.equalsIgnoreCase("set-string")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The set-string verb requires a name parameter"); } String body = getBody(req); // a value of "" is legit Interpreter i = getInterpreter(contextId); i.unset(name); i.set(name, body); sendNoResponse(res); } else if (verb.equalsIgnoreCase("set-binary")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The set-binary verb requires a name parameter"); } String body = getBody(req); // a value of "" is legit byte[] bodyBytes = hexDecode(body); // later could do this streaming for speed Interpreter i = getInterpreter(contextId); i.unset(name); i.set(name, bodyBytes); sendNoResponse(res); } else if (verb.equalsIgnoreCase("eval")) { String body = getBody(req); if (body == null || body.equals("")) { throw new ClientProblemException( "The eval verb requires a post body containing code to eval"); } Interpreter i = getInterpreter(contextId); i.eval(body); sendNoResponse(res); } else if (verb.equalsIgnoreCase("eval-get")) { String body = getBody(req); if (body == null || body.equals("")) { throw new ClientProblemException( "The eval-get verb requires a post body containing code to eval"); } Interpreter i = getInterpreter(contextId); Object o = i.eval(body); if (o instanceof byte[]) { sendBinaryResponse(res, (byte[]) o); } else if (o instanceof String) { sendStringResponse(res, (String) o); } else { sendXQueryResponse(res, o); } } else if (verb.equalsIgnoreCase("unset")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The unset verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); i.unset(name); sendNoResponse(res); } else if (verb.equalsIgnoreCase("end")) { endInterpreter(contextId); sendNoResponse(res); } else if (verb.equalsIgnoreCase("source")) { String name = req.getParameter("name"); if (name == null || name.equals("")) { throw new ClientProblemException("The source verb requires a name parameter"); } Interpreter i = getInterpreter(contextId); i.source(name); sendNoResponse(res); } else { throw new ClientProblemException("Unrecognized POST verb: " + verb); } } } catch (TargetError e) { Throwable target = e.getTarget(); Log.log(e); Log.log("Target: " + target); sendServerProblemResponse( res, target.getClass().getName() + ": " + target.getMessage() + " when executing Java code: " + e.getErrorText()); // include full trace? } catch (EvalError e) { Log.log(e); sendServerProblemResponse( res, e.getClass().getName() + ": " + e.getMessage()); // include full trace? } catch (ClientProblemException e) { Log.log(e); sendClientProblemResponse(res, e.getMessage()); } catch (ServerProblemException e) { Log.log(e); sendServerProblemResponse(res, e.getMessage()); } }