static void nashornCompiledScript(String code) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    CompiledScript compiled = ((Compilable) engine).compile(code);

    Object result = null;
    ScriptContext context = new SimpleScriptContext();
    Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE);
    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        engineScope.put("value", "12345678");
        result = compiled.eval(context);
      }
      long stop = System.nanoTime();
      System.out.println(
          "Run "
              + (i * BATCH + 1)
              + "-"
              + ((i + 1) * BATCH)
              + ": "
              + Math.round((stop - start) / BATCH / 1000)
              + " us");
      total += (stop - start);
    }

    System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us");
    System.out.println(
        "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString());
  }
  public static void main(String[] args) {
    // Script Engine instantiation using ServiceProvider - this will
    // look in the classpath for a file
    //  /META-INF/services/javax.script.ScriptEngineFactory
    // where the AbclScriptEngineFactory is registered
    ScriptEngine lispEngine = new ScriptEngineManager().getEngineByExtension("lisp");

    // Alternatively, you can directly instantiate the script engine:

    // ScriptEngineManager scriptManager = new ScriptEngineManager();
    // scriptManager.registerEngineExtension("lisp", new AbclScriptEngineFactory());
    // ScriptEngine lispEngine = scriptManager.getEngineByExtension("lisp");

    // (thanks to Peter Tsenter for suggesting this)

    // Accessing variables
    System.out.println();
    System.out.println("*package* = " + lispEngine.get("*package*"));
    Object someValue = new Object();
    lispEngine.put("someVariable", someValue);
    System.out.println("someVariable = " + lispEngine.get("someVariable"));
    try {
      // Interpretation (also from streams)
      lispEngine.eval("(defun hello (arg) (print (list arg someVariable)) (terpri))");

      // Direct function invocation
      ((Invocable) lispEngine).invokeFunction("hello", "world");

      // Implementing a Java interface in Lisp
      lispEngine.eval("(defun compare-to (&rest args) 42)");
      Comparable c = ((Invocable) lispEngine).getInterface(java.lang.Comparable.class);
      System.out.println("compareTo: " + c.compareTo(null));

      // Compilation!
      lispEngine.eval(
          "(defmacro slow-compiling-macro (arg) (dotimes (i 1000000) (incf i)) `(print ,arg))");

      long millis = System.currentTimeMillis();
      lispEngine.eval("(slow-compiling-macro 42)");
      millis = System.currentTimeMillis() - millis;
      System.out.println("interpretation took " + millis);

      millis = System.currentTimeMillis();
      CompiledScript cs = ((Compilable) lispEngine).compile("(slow-compiling-macro 42)");
      millis = System.currentTimeMillis() - millis;
      System.out.println("compilation took " + millis);

      millis = System.currentTimeMillis();
      cs.eval();
      millis = System.currentTimeMillis() - millis;
      System.out.println("evaluation took " + millis);

      millis = System.currentTimeMillis();
      cs.eval();
      millis = System.currentTimeMillis() - millis;
      System.out.println("evaluation took " + millis);

      // Ecc. ecc.
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (ScriptException e) {
      e.printStackTrace();
    }
  }
 @Test
 public void shouldCompileScript() throws Exception {
   final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();
   final CompiledScript script = gremlinExecutor.compile("1+1").get();
   assertEquals(2, script.eval());
   gremlinExecutor.close();
 }
Beispiel #4
0
  /** Test of compile method, of class Jsr223JRubyEngine. */
  @Test
  public void testCompile_Reader() throws Exception {
    logger1.info("[compile reader]");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.localcontext.scope", "singlethread");
      System.setProperty("org.jruby.embed.localvariable.behavior", "transient");
      ScriptEngineManager manager = new ScriptEngineManager();
      instance = manager.getEngineByName("jruby");
    }
    String filename = basedir + "/src/test/ruby/org/jruby/embed/ruby/proverbs_of_the_day.rb";
    Reader reader = new FileReader(filename);

    instance.put("$day", -1);
    CompiledScript cs = ((Compilable) instance).compile(reader);
    String result = (String) cs.eval();
    String expResult = "A rolling stone gathers no moss.";
    assertEquals(expResult, result);
    result = (String) cs.eval();
    expResult = "A friend in need is a friend indeed.";
    assertEquals(expResult, result);
    result = (String) cs.eval();
    expResult = "Every garden may have some weeds.";
    assertEquals(expResult, result);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #5
0
  /** Test of compile method, of class Jsr223JRubyEngine. */
  @Test
  public void testCompile_String() throws Exception {
    logger1.info("[compile string]");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.localcontext.scope", "singlethread");
      System.setProperty("org.jruby.embed.localvariable.behavior", "global");
      ScriptEngineManager manager = new ScriptEngineManager();
      instance = manager.getEngineByName("jruby");
    }
    String script =
        "def norman_window(x, y)\n"
            + "return get_area(x, y), get_perimeter(x, y)\n"
            + "end\n"
            + "def get_area(x, y)\n"
            + "x * y + Math::PI / 8.0 * x ** 2.0\n"
            + "end\n"
            + "def get_perimeter(x, y)\n"
            + "x + 2.0 * y + Math::PI / 2.0 * x\n"
            + "end\n"
            + "norman_window(2, 1)";
    CompiledScript cs = ((Compilable) instance).compile(script);
    List<Double> result = (List<Double>) cs.eval();
    assertEquals(3.570796327, result.get(0), 0.000001);
    assertEquals(7.141592654, result.get(1), 0.000001);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
 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);
 }
 @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);
 }
 public double[] fitfunc(double[] fitparams) {
   Bindings b = engine.createBindings();
   for (int i = 0; i < 10; i++) b.put("P" + (i + 1), fitparams[i]);
   /*String script1="P1="+fitparams[0]+"; "+
   "P2="+fitparams[1]+"; "+
   "P3="+fitparams[2]+"; "+
   "P4="+fitparams[3]+"; "+
   "P5="+fitparams[4]+"; "+
   "P6="+fitparams[5]+"; "+
   "P7="+fitparams[6]+"; "+
   "P8="+fitparams[7]+"; "+
   "P9="+fitparams[8]+"; "+
   "P10="+fitparams[9]+"; "+
   exdef+"; x=";
   String script2="; retval="+function+";";*/
   try {
     double[] temp = new double[tempx.length];
     for (int i = 0; i < tempx.length; i++) {
       // temp[i]=((Double)engine.eval(script1+(double)tempx[i]+script2)).doubleValue();
       b.put("x", tempx[i]);
       b.put("y", tempdata[i]);
       temp[i] = (Double) cs.eval(b);
     }
     return temp;
   } catch (Exception e) {
     IJ.log(e.getMessage());
     return null;
   }
 }
Beispiel #9
0
 public void execute() {
   try {
     compiledScript.eval();
   } catch (ScriptException e) {
     onScriptError(e);
     return;
   }
 }
  @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());
  }
Beispiel #11
0
 public void execute(Bindings bindings) {
   try {
     for (String key : bindings.keySet()) {
       engine.put(key, bindings.get(key));
     }
     compiledScript.eval();
   } catch (ScriptException e) {
     onScriptError(e);
     return;
   }
 }
Beispiel #12
0
 @Override
 public List<Object> next() throws TranslatorException, DataNotAvailableException {
   // create and return one row at a time for your resultset.
   if (resultsIt.hasNext()) {
     List<Object> r = new ArrayList<Object>(projects.size());
     Object o = resultsIt.next();
     sc.setAttribute(OBJECT_NAME, o, ScriptContext.ENGINE_SCOPE);
     for (CompiledScript cs : this.projects) {
       if (cs == null) {
         r.add(o);
         continue;
       }
       try {
         r.add(cs.eval(sc));
       } catch (ScriptException e) {
         throw new TranslatorException(e);
       }
     }
     return r;
   }
   return null;
 }
Beispiel #13
0
  /**
   * Perform mediation with static inline script of the given scripting language
   *
   * @param synCtx message context
   * @return true, or the script return value
   * @throws ScriptException For any errors , when compile , run the script
   */
  private Object mediateForInlineScript(MessageContext synCtx) throws ScriptException {
    ScriptMessageContext scriptMC = new ScriptMessageContext(synCtx, xmlHelper);
    processJSONPayload(synCtx, scriptMC);
    Bindings bindings = scriptEngine.createBindings();
    bindings.put(MC_VAR_NAME, scriptMC);

    Object response;
    if (compiledScript != null) {
      response = compiledScript.eval(bindings);
    } else {
      response = scriptEngine.eval(scriptSourceCode, bindings);
    }

    return response;
  }
  /*
    Helper method called by the {@link Context} for executing script with
    the bindings within the context
  */
  void execute(Bindings bindings, List<CompiledScript> injectedScripts) throws ScriptException {
    // First execute the head parts
    for (CompiledScript script : headScripts) {
      script.eval(bindings);
    }

    // Between the head and the body, execute the injected scripts
    // The injected scripts are appended in the head element
    for (CompiledScript script : injectedScripts) {
      script.eval(bindings);
    }

    // The body scripts are executed at the end
    for (CompiledScript script : bodyScripts) {
      script.eval(bindings);
    }
  }
  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);
      }
    }
  }