コード例 #1
0
  /**
   * Constructor, compiles script, put header in the bindings
   *
   * @param scriptReader reader containing the script. will be closed.
   * @param header the header to be injected in the javascript context
   */
  protected AbstractJavascriptFilter(final Reader scriptReader, final HEADER header) {
    final ScriptEngineManager manager = new ScriptEngineManager();
    /* get javascript engine */
    final ScriptEngine engine = manager.getEngineByName("js");
    if (engine == null) {
      CloserUtil.close(scriptReader);
      throw new RuntimeScriptException(
          "The embedded 'javascript' engine is not available in java. "
              + "Do you use the SUN/Oracle Java Runtime ?");
    }
    if (scriptReader == null) {
      throw new RuntimeScriptException("missing ScriptReader.");
    }

    try {
      final Compilable compilingEngine = getCompilable(engine);
      this.script = compilingEngine.compile(scriptReader);
    } catch (ScriptException err) {
      throw new RuntimeScriptException("Script error in input", err);
    } finally {
      CloserUtil.close(scriptReader);
    }

    /*
     * create the javascript bindings and put the file header in that
     * context
     */
    this.bindings = new SimpleBindings();
    this.bindings.put(DEFAULT_HEADER_KEY, header);
  }
コード例 #2
0
 public Object eval(ScriptEngine engine, String script, ScriptContext context)
     throws ScriptException {
   if (engine instanceof Compilable && Config.SCRIPT_ALLOW_COMPILATION) {
     Compilable eng = (Compilable) engine;
     CompiledScript cs = eng.compile(script);
     return context != null ? cs.eval(context) : cs.eval();
   } else return context != null ? engine.eval(script, context) : engine.eval(script);
 }
コード例 #3
0
 @Test
 public void testCompilable() throws ScriptException {
   final Compilable compilableFrege = (Compilable) frege;
   final CompiledScript compiled =
       compilableFrege.compile("fib = 0 : 1 : zipWith (+) fib (tail fib)");
   compiled.eval();
   final Object actual = frege.eval("show $ take 6 fib");
   final Object expected = "[0, 1, 1, 2, 3, 5]";
   assertEquals(expected, actual);
 }
コード例 #4
0
ファイル: JavascriptEditor.java プロジェクト: Cloudyhh/gmilk
 public boolean compile() {
   String script = getTextAsString();
   try {
     compiledScript = compiler.compile(script);
   } catch (ScriptException e) {
     onScriptError(e);
     return false;
   }
   return true;
 }
コード例 #5
0
  @Test
  public void testNashornWithCompile() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine =
        engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);

    Compilable compiler = (Compilable) engine;
    assertNotNull(compiler);

    InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js");
    assertNotNull(stream);
    String js = IOUtils.toString(stream);

    CompiledScript compiled = compiler.compile(new StringReader(js));

    engine.put("mapper", new Mapper());

    compiled.eval(engine.getContext());
    assertEquals(
        "1"
            + System.lineSeparator()
            + "str"
            + System.lineSeparator()
            + "[1, 2, {a=1, b=2}]"
            + System.lineSeparator()
            + "{a=1, b=2}"
            + System.lineSeparator()
            + "This is a string"
            + System.lineSeparator()
            + "This is a string"
            + System.lineSeparator()
            + "2"
            + System.lineSeparator()
            + "[A, B, C]"
            + System.lineSeparator()
            + "{a=salut, b=from java}"
            + System.lineSeparator()
            + "done"
            + System.lineSeparator(),
        outContent.toString());
  }
コード例 #6
0
  @Post
  @At("/:port/interceptor/request")
  public Reply<?> addRequestInterceptor(@Named("port") int port, Request<String> request)
      throws IOException, ScriptException {
    LegacyProxyServer proxy = proxyManager.get(port);
    if (proxy == null) {
      return Reply.saying().notFound();
    }

    if (!(proxy instanceof ProxyServer)) {
      return Reply.saying().badRequest();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    request.readTo(baos);

    ScriptEngineManager mgr = new ScriptEngineManager();
    final ScriptEngine engine = mgr.getEngineByName("JavaScript");
    Compilable compilable = (Compilable) engine;
    final CompiledScript script = compilable.compile(baos.toString());

    proxy.addRequestInterceptor(
        new RequestInterceptor() {
          @Override
          public void process(BrowserMobHttpRequest request, Har har) {
            Bindings bindings = engine.createBindings();
            bindings.put("request", request);
            bindings.put("har", har);
            bindings.put("log", LOG);
            try {
              script.eval(bindings);
            } catch (ScriptException e) {
              LOG.error("Could not execute JS-based response interceptor", e);
            }
          }
        });

    return Reply.saying().ok();
  }
コード例 #7
0
 boolean init_functions() {
   GenericDialog gd = new GenericDialog("Fitting Options");
   gd.addStringField("Extra Definitions", exdef, 50);
   gd.addCheckbox("Weight Using Plot Errors", false);
   gd.addStringField("Weighting Equation (y is for data)", weightfunction, 50);
   gd.addStringField("Fit_Equation", function, 50);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   exdef = gd.getNextString();
   boolean errweights = gd.getNextBoolean();
   weightfunction = gd.getNextString();
   function = gd.getNextString();
   // first initialize the weights
   weights = new float[tempdata.length];
   if (errweights
       || weightfunction.equals("")
       || weightfunction == null
       || weightfunction == "1.0") {
     if (errweights) {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f / (errs[i] * errs[i]);
     } else {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f;
     }
   } else {
     for (int i = 0; i < tempdata.length; i++) {
       String script =
           "y =" + tempdata[i] + "; " + "x =" + tempx[i] + "; " + "retval=" + weightfunction + ";";
       Double temp = new Double(0.0);
       try {
         temp = (Double) engine.eval(script);
       } catch (Exception e) {
         IJ.log(e.getMessage());
       }
       if (!(temp.isInfinite() || temp.isNaN())) {
         weights[i] = temp.floatValue();
       }
     }
   }
   // now compile the function script
   try {
     String script1 = exdef + "; retval=" + function + ";";
     cs = ce.compile(script1);
   } catch (Exception e) {
     IJ.log(e.toString());
     return false;
   }
   return true;
 }
コード例 #8
0
  /**
   * Return a compiled version of the provided script.
   *
   * @param content the script to compile.
   * @param engine the script engine.
   * @return the compiled version of the script.
   * @throws ScriptException failed to compile the script.
   */
  protected CompiledScript getCompiledScript(String content, Compilable engine)
      throws ScriptException {
    // TODO: add caching

    return engine.compile(content);
  }
コード例 #9
0
  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);
      }
    }
  }