public CompiledScriptCache loadCompiledScriptCache() {
   if (Config.SCRIPT_CACHE) {
     File file = new File(SCRIPT_FOLDER, "CompiledScripts.cache");
     if (file.isFile()) {
       ObjectInputStream ois = null;
       try {
         ois = new ObjectInputStream(new FileInputStream(file));
         CompiledScriptCache cache = (CompiledScriptCache) ois.readObject();
         return cache;
       } catch (InvalidClassException e) {
         _log.fatal(
             "Failed loading Compiled Scripts Cache, invalid class (Possibly outdated).", e);
       } catch (IOException e) {
         _log.fatal("Failed loading Compiled Scripts Cache from file.", e);
       } catch (ClassNotFoundException e) {
         _log.fatal("Failed loading Compiled Scripts Cache, class not found.", e);
       } finally {
         try {
           ois.close();
         } catch (Exception e) {
         }
       }
       return new CompiledScriptCache();
     } else return new CompiledScriptCache();
   }
   return null;
 }
 public static String getClassForFile(File script) {
   String path = script.getAbsolutePath();
   String scpPath = SCRIPT_FOLDER.getAbsolutePath();
   if (path.startsWith(scpPath)) {
     int idx = path.lastIndexOf('.');
     return path.substring(scpPath.length() + 1, idx);
   }
   return null;
 }
  public void reportScriptFileError(File script, ScriptException e) {
    String dir = script.getParent();
    String name = script.getName() + ".error.log";
    if (dir != null) {
      File file = new File(dir + "/" + name);
      FileOutputStream fos = null;
      try {
        if (!file.exists()) {
          file.createNewFile();
        }

        fos = new FileOutputStream(file);
        String errorHeader =
            "Error on: "
                + file.getCanonicalPath()
                + "\r\nLine: "
                + e.getLineNumber()
                + " - Column: "
                + e.getColumnNumber()
                + "\r\n\r\n";
        fos.write(errorHeader.getBytes());
        fos.write(e.getMessage().getBytes());
        _log.warn(
            "Failed executing script: "
                + script.getAbsolutePath()
                + ". See "
                + file.getName()
                + " for details.");
      } catch (IOException ioe) {
        _log.warn(
            "Failed executing script: "
                + script.getAbsolutePath()
                + "\r\n"
                + e.getMessage()
                + "Additionally failed when trying to write an error report on script directory. Reason: "
                + ioe.getMessage());
        ioe.printStackTrace();
      } finally {
        try {
          fos.close();
        } catch (Exception e1) {
        }
      }
    } else {
      _log.warn(
          "Failed executing script: "
              + script.getAbsolutePath()
              + "\r\n"
              + e.getMessage()
              + "Additionally failed when trying to write an error report on script directory.");
    }
  }
  public NashornProcessor(File documentRoot, String documentPath)
      throws ScriptException, IOException, SAXException {
    // The document root must be a valid directory
    assert (documentRoot.isDirectory());

    // The document root is needed for evaluating script files that are
    // marked with absolute path in the src attribute
    this.documentRoot = documentRoot;

    // Let's see if we could find the document that has been inferred
    File file = new File(documentRoot, documentPath);

    // Keep the parent of this file for relative path based file access
    basePath = file.getParentFile();
    document = HTMLDocument.parse(new FileInputStream(file));

    ScriptEngine e = new ScriptEngineManager().getEngineByName("nashorn");
    assert (e instanceof NashornScriptEngine);
    engine = (NashornScriptEngine) e;

    // TODO get base href and implement set basePath and use it accordingly
    // The basePath can also have full URL which makes it tricky
    // HTMLElement[] scriptElements = document.getElementsByTagName("base");

    HTMLElement[] parts = {document.getHead(), document.getBody()};
    CompiledScript[][] res = new CompiledScript[2][];

    for (int i = 0; i < parts.length; ++i) {

      HTMLElement[] scriptElements = parts[i].getElementsByTagName("script");
      res[i] = new CompiledScript[scriptElements.length];

      int idx = 0;
      for (HTMLElement scriptElement : scriptElements) {
        // if the element has a src tag then we work on a file otherwise, we
        // expect either a CDATA section or a TEXT section within the
        // script element
        String scriptFile = scriptElement.getAttribute("src");
        CompiledScript script;
        if (scriptFile == null) {
          script = loadTextScript(scriptElement);
        } else {
          script = loadFileScript(scriptFile);
        }
        res[i][idx++] = script;
      }
    }

    headScripts = res[0];
    bodyScripts = res[1];
  }
Example #5
0
 public static String[] get_filelist(String path, boolean nodirs, boolean nofiles) {
   File folder = new File(path);
   if (folder.isDirectory()) {
     File[] listOfFiles = folder.listFiles();
     java.util.Vector<String> r = new java.util.Vector<String>();
     for (int i = 0; listOfFiles != null && i < listOfFiles.length; i++) {
       if ((listOfFiles[i].isFile() && !nofiles) || (listOfFiles[i].isDirectory() && !nodirs)) {
         r.add(listOfFiles[i].getName());
       }
     }
     return r.toArray(new String[0]);
   } else {
     return null; // A: no existe o no es directorio
   }
 }
 private void executeAllScriptsInDirectory(
     File dir, boolean recurseDown, int maxDepth, int currentDepth) {
   if (dir.isDirectory()) {
     for (File file : dir.listFiles()) {
       if (file.isDirectory() && recurseDown && maxDepth > currentDepth) {
         if (Config.SCRIPT_DEBUG) {
           _log.info("Entering folder: " + file.getName());
         }
         this.executeAllScriptsInDirectory(file, recurseDown, maxDepth, currentDepth + 1);
       } else if (file.isFile()) {
         try {
           String name = file.getName();
           int lastIndex = name.lastIndexOf('.');
           String extension;
           if (lastIndex != -1) {
             extension = name.substring(lastIndex + 1);
             ScriptEngine engine = getEngineByExtension(extension);
             if (engine != null) {
               this.executeScript(engine, file);
             }
           }
         } catch (FileNotFoundException e) {
           // should never happen
           e.printStackTrace();
         } catch (ScriptException e) {
           reportScriptFileError(file, e);
           // e.printStackTrace();
         }
       }
     }
   } else
     throw new IllegalArgumentException(
         "The argument directory either doesnt exists or is not an directory.");
 }
Example #7
0
 public static void main(String[] args) throws Exception {
   System.out.println("\nTest7\n");
   File file = new File(System.getProperty("test.src", "."), "Test7.js");
   Reader r = new FileReader(file);
   ScriptEngineManager m = new ScriptEngineManager();
   ScriptEngine eng = Helper.getJsEngine(m);
   if (eng == null) {
     System.out.println("Warning: No js engine found; test vacuously passes.");
     return;
   }
   eng.put("filename", file.getAbsolutePath());
   eng.eval(r);
   String str = (String) eng.get("firstLine");
   // do not change first line in Test7.js -- we check it here!
   if (!str.equals("//this is the first line of Test7.js")) {
     throw new RuntimeException("unexpected first line");
   }
 }
 private void preConfigure() {
   // Jython sys.path
   String dataPackDirForwardSlashes = SCRIPT_FOLDER.getPath().replaceAll("\\\\", "/");
   String configScript = "import sys;sys.path.insert(0,'" + dataPackDirForwardSlashes + "');";
   try {
     this.eval("jython", configScript);
   } catch (ScriptException e) {
     _log.fatal("Failed preconfiguring jython: " + e.getMessage());
   }
 }
  public void executeScriptsList(File list) throws IOException {
    if (list.isFile()) {
      LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(list)));
      String line;
      File file;

      while ((line = lnr.readLine()) != null) {
        String[] parts = line.trim().split("#");

        if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
          line = parts[0];

          if (line.endsWith("/**")) {
            line = line.substring(0, line.length() - 3);
          } else if (line.endsWith("/*")) {
            line = line.substring(0, line.length() - 2);
          }

          file = new File(SCRIPT_FOLDER, line);

          if (file.isDirectory() && parts[0].endsWith("/**")) {
            this.executeAllScriptsInDirectory(file, true, 32);
          } else if (file.isDirectory() && parts[0].endsWith("/*")) {
            this.executeAllScriptsInDirectory(file);
          } else if (file.isFile()) {
            try {
              this.executeScript(file);
            } catch (ScriptException e) {
              reportScriptFileError(file, e);
            }
          } else {
            _log.warn(
                "Failed loading: ("
                    + file.getCanonicalPath()
                    + ") @ "
                    + list.getName()
                    + ":"
                    + lnr.getLineNumber()
                    + " - Reason: doesnt exists or is not a file.");
          }
        }
      }
      lnr.close();
    } else
      throw new IllegalArgumentException(
          "Argument must be an file containing a list of scripts to be loaded");
  }
  public void executeScript(File file) throws ScriptException, FileNotFoundException {
    String name = file.getName();
    int lastIndex = name.lastIndexOf('.');
    String extension;
    if (lastIndex != -1) {
      extension = name.substring(lastIndex + 1);
    } else
      throw new ScriptException(
          "Script file ("
              + name
              + ") doesnt has an extension that identifies the ScriptEngine to be used.");

    ScriptEngine engine = getEngineByExtension(extension);
    if (engine == null)
      throw new ScriptException("No engine registered for extension (" + extension + ")");
    else {
      this.executeScript(engine, file);
    }
  }
  public void executeScript(ScriptEngine engine, File file)
      throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (Config.SCRIPT_DEBUG) {
      _log.info("Loading Script: " + file.getAbsolutePath());
    }

    if (Config.SCRIPT_ERROR_LOG) {
      String name = file.getAbsolutePath() + ".error.log";
      File errorLog = new File(name);
      if (errorLog.isFile()) {
        errorLog.delete();
      }
    }

    if (engine instanceof Compilable && Config.SCRIPT_ALLOW_COMPILATION) {
      ScriptContext context = new SimpleScriptContext();
      context.setAttribute(
          "mainClass",
          getClassForFile(file).replace('/', '.').replace('\\', '.'),
          ScriptContext.ENGINE_SCOPE);
      context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
      context.setAttribute(
          "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
      context.setAttribute(
          "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
      context.setAttribute(
          JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE);

      setCurrentLoadingScript(file);
      ScriptContext ctx = engine.getContext();
      try {
        engine.setContext(context);
        if (Config.SCRIPT_CACHE) {
          CompiledScript cs = _cache.loadCompiledScript(engine, file);
          cs.eval(context);
        } else {
          Compilable eng = (Compilable) engine;
          CompiledScript cs = eng.compile(reader);
          cs.eval(context);
        }
      } finally {
        engine.setContext(ctx);
        setCurrentLoadingScript(null);
        context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
        context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
      }
    } else {
      ScriptContext context = new SimpleScriptContext();
      context.setAttribute(
          "mainClass",
          getClassForFile(file).replace('/', '.').replace('\\', '.'),
          ScriptContext.ENGINE_SCOPE);
      context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
      context.setAttribute(
          "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
      context.setAttribute(
          "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
      setCurrentLoadingScript(file);
      try {
        engine.eval(reader, context);
      } finally {
        setCurrentLoadingScript(null);
        engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
        engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
      }
    }
  }
Example #12
0
 public static String temp_filePath(String namePattern, String ext)
     throws IOException, FileNotFoundException {
   File temp = File.createTempFile("temp-file-name", ".tmp");
   return temp.getAbsolutePath();
 }