Exemplo n.º 1
0
 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); }");
 }
Exemplo n.º 3
0
Arquivo: BSH.java Projeto: Zengwn/jPOS
 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);
   }
 }
Exemplo n.º 4
0
 public void set_variable(String s, Object o) {
   try {
     main_interpreter.set(s, o);
   } catch (EvalError evalError) {
     evalError.printStackTrace();
   }
 }
Exemplo n.º 5
0
  /**
   * 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
      }
    }
  } // }}}
Exemplo n.º 6
0
 /**
  * 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 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);
    }
  }
Exemplo n.º 8
0
  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);
        }
    }
  }
Exemplo n.º 9
0
  public void configure(Interpreter interpreter) {
    if (LOGGER.isDebugEnabled()) LOGGER.debug("Starting server on 9999");
    try {
      interpreter.set("currentModel", null);
      URL commonURL =
          Controller.class.getClassLoader().getResource("org/jactr/tools/shell/common.bsh");
      interpreter.set("commonURL", commonURL);
      interpreter.eval("source(commonURL);");
      interpreter.eval("importCommands(\"org.jactr.tools.shell.commands\");");
      interpreter.eval("server(9999);");
      interpreter.set("runState", "[?]");
    } catch (EvalError e) {
      /** Error : */
      LOGGER.error("Could not configure default settings ", e);
    }

    configureOthers(interpreter);
  }
Exemplo n.º 10
0
 synchronized void createInterpreter() {
   // create interpreter just-in-time
   if (interpreter == null) {
     interpreter = new Interpreter();
     try {
       interpreter.set("bsh_prot", this);
     } catch (EvalError evalError) {
     }
   }
 }
Exemplo n.º 11
0
  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;
  }
Exemplo n.º 12
0
  /**
   * 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);
    }
  }
Exemplo n.º 13
0
 /**
  * 初始化变量环境
  *
  * @param i
  * @throws EvalError
  */
 private void initEvalContext(Interpreter i) throws EvalError {
   Set vars = this.context.getVars();
   Iterator iterator = vars.iterator();
   while (iterator.hasNext()) {
     String var = iterator.next() + "";
     Object obj = context.getVar(var);
     try {
       i.set(var, obj);
     } catch (EvalError e) {
       e.printStackTrace();
     }
   }
 }
Exemplo n.º 14
0
 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);
   }
 }
Exemplo n.º 15
0
  /**
   * 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;
    }
  }
Exemplo n.º 16
0
 protected void initializeToolbox(ToolboxDialog toolbox) {
   try {
     toolbox.setIconImage(icon.getImage());
     final JConsole console = new JConsole();
     console.setPreferredSize(new Dimension(430, 240));
     console.print(
         I18N.get("ui.plugin.BeanShellPlugIn.the-workbenchcontext-may-be-referred-to-as-wc"));
     console.print(
         I18N.get(
             "ui.plugin.BeanShellPlugIn.warning-pasting-in-multiple-statements-may-cause-the-application-to-freeze"));
     toolbox.getCenterPanel().add(console, BorderLayout.CENTER);
     Interpreter interpreter = new Interpreter(console);
     interpreter.setClassLoader(
         toolbox.getContext().getWorkbench().getPlugInManager().getClassLoader());
     interpreter.set("wc", toolbox.getContext());
     interpreter.eval("setAccessibility(true)");
     interpreter.eval("import com.vividsolutions.jts.geom.*");
     interpreter.eval("import com.vividsolutions.jump.feature.*");
     new Thread(interpreter).start();
   } catch (EvalError e) {
     toolbox.getContext().getErrorHandler().handleThrowable(e);
   }
 }
  /**
   * resolution des variables d'une string puis evaluation dynamique d'une string de la forme
   * $eval{{.....}}
   */
  public final String resolveAndEvalString(String pStr)
      throws IOException, IllegalArgumentException {
    int index = pStr.indexOf("$eval{{");
    if (index == -1) {
      return resolveString(pStr);
    } else {
      if (index != 0) {
        throw new IllegalArgumentException(
            "(Unable to evaluate "
                + pStr
                + " because string is not beginning with \"$eval{{\" sequence.");
      }

      int index_fin = pStr.indexOf("}}");

      if (index_fin != pStr.length() - 2) {
        throw new IllegalArgumentException(
            "(unable to evaluate " + pStr + " because string is not endding with \"}}\" sequence.");
      }

      String resolvedString = pStr.substring(0, index_fin);
      resolvedString = resolvedString.substring(7);
      resolvedString = resolveString(resolvedString);

      // evaluation dynamique
      String evaluatedString = null;
      try {
        Interpreter bsh = new Interpreter();
        bsh.set("value", new String());
        bsh.eval(resolvedString);
        evaluatedString = (String) bsh.get("value");
      } catch (EvalError e) {
        throw new IllegalArgumentException("(unable to evaluate " + resolvedString, e);
      }
      return evaluatedString;
    }
  }
  /**
   * 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);
    }
  }
Exemplo n.º 19
0
  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());
    }
  }
Exemplo n.º 20
0
 @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;
 }
Exemplo n.º 21
0
  private static Interpreter getInterpreter(String contextId) throws EvalError {
    // Get the appropriate interpreter
    Interpreter i = null;
    boolean createdInterp = false;
    synchronized (interpreters) { // serialize two gets of the same name
      i = interpreters.get(contextId);
      if (i == null) {
        i = new Interpreter();
        interpreters.put(contextId, i);
        createdInterp = true;
      }
    }
    if (createdInterp) {
      Log.log("Created context: " + contextId + " (" + i + ")");

      // Now configure stdin and stdout to capture 10k of content
      // Store references to the circular buffers within the interpreter itself.
      // This provides a nice place to store them plus theoretically allows
      // advanced use from within the bsh environment.
      // On Windows print() outputs \r\n but in XQuery that's normalized to \n
      // so the 10k of Java buffer may produce less than 10k of content in XQuery!
      OutputStream circularOutput = new CircularByteArrayOutputStream(10240);
      PrintStream printOutput = new PrintStream(circularOutput);
      i.setOut(printOutput);
      i.set("mljamout", circularOutput);

      OutputStream circularError = new CircularByteArrayOutputStream(10240);
      PrintStream printError = new PrintStream(circularError);
      i.setErr(printError);
      i.set("mljamerr", circularError);

      // Capture the built-in System.out and System.err also.
      // (Commented out since System appears global, can't do per interpreter.)
      // i.set("mljamprintout", printOutput);
      // i.set("mljamprinterr", printError);
      // i.eval("System.setOut(mljamprintout);");
      // i.eval("System.setErr(mljamprinterr);");

      // Need to expose hexdecode() and base64decode() built-in functions
      i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }");
      i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }");

      // Let's tell the context what its id is
      i.set("mljamid", contextId);
    }

    // Update the last accessed time, used for cleaning
    i.set("mljamlast", System.currentTimeMillis());

    // If it's been long enough, go snooping for stale contexts
    if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) {
      Log.log("Initiated periodic scan for stale context objects");
      lastClean = System.currentTimeMillis();
      Iterator<Interpreter> itr = interpreters.values().iterator();
      while (itr.hasNext()) {
        Interpreter interp = itr.next();
        Long last = (Long) interp.get("mljamlast");
        if (System.currentTimeMillis() > last + STALE_TIMEOUT) {
          itr.remove();
          Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")");
        } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT)
            && ("" + interp.get("mljamid")).startsWith("temp:")) {
          itr.remove();
          Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")");
        }
      }
    }

    return i;
  }