Esempio n. 1
0
  /** {@inheritDoc} */
  public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces)
      throws IOException, ScriptCompilationException {
    // TODO: how to do this when running under Tomcat?
    ContextHandler handler = WebAppContext.getCurrentWebAppContext();
    String basePath = "";
    if (handler != null) {
      File root = handler.getBaseResource().getFile();
      if (root != null && root.exists()) {
        basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
      }
    }

    String strScript = scriptSourceLocator.getScriptAsString();
    if (scriptInterfaces.length > 0) {
      try {
        PySystemState state = new PySystemState();
        if (!"".equals(basePath)) {
          // Add webapp paths that can contain classes and .jar files to python search path
          state.path.insert(0, Py.newString(basePath + "classes"));
          File jarRoot = new File(basePath + "lib");
          if (jarRoot.exists()) {
            for (String filename :
                jarRoot.list(
                    new FilenameFilter() {
                      public boolean accept(File dir, String name) {
                        return (name.endsWith(".jar"));
                      }
                    })) {
              state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
            }
          }
        }
        PythonInterpreter interp = new PythonInterpreter(null, state);
        interp.exec(strScript);
        PyObject getInstance = interp.get("getInstance");
        if (!(getInstance instanceof PyFunction)) {
          throw new ScriptCompilationException("\"getInstance\" is not a function.");
        }
        PyObject _this;
        if (arguments == null) {
          _this = ((PyFunction) getInstance).__call__();
        } else {
          PyObject[] args = new PyObject[arguments.length];
          for (int i = 0; i < arguments.length; i++) {
            args[i] = new PyJavaInstance(arguments[i]);
          }
          _this = ((PyFunction) getInstance).__call__(args);
        }
        return _this.__tojava__(scriptInterfaces[0]);
      } catch (Exception ex) {
        logger.error("Error while loading script.", ex);
        if (ex instanceof IOException) {
          // Raise to caller
          throw (IOException) ex;
        } else if (ex instanceof ScriptCompilationException) {
          // Raise to caller
          throw (ScriptCompilationException) ex;
        }

        throw new ScriptCompilationException(ex.getMessage());
      }
    }
    logger.error("No scriptInterfaces provided.");
    return null;
  }