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());
  }
Пример #2
1
  /** Test of getBindings method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetBindings() throws ScriptException {
    logger1.info("getBindings");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.localcontext.scope", "singlethread");
      System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");
      ScriptEngineManager manager = new ScriptEngineManager();
      instance = manager.getEngineByName("jruby");
    }

    instance.eval("p = 9.0");
    instance.eval("q = Math.sqrt p");
    Double expResult = 9.0;
    int scope = ScriptContext.ENGINE_SCOPE;
    Bindings result = instance.getBindings(scope);
    assertEquals(expResult, (Double) result.get("p"), 0.01);
    expResult = 3.0;
    assertEquals(expResult, (Double) result.get("q"), 0.01);

    scope = ScriptContext.GLOBAL_SCOPE;
    result = instance.getBindings(scope);
    // Bug of livetribe javax.script package impl.
    // assertTrue(result instanceof SimpleBindings);
    // assertEquals(0, result.size());
    JRubyScriptEngineManager manager2 = new JRubyScriptEngineManager();
    instance = (JRubyEngine) manager2.getEngineByName("jruby");
    result = instance.getBindings(scope);
    assertTrue(result instanceof SimpleBindings);
    assertEquals(0, result.size());

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #3
0
  public Engine(List<String> javascriptFilesToLoad) throws ScriptException, IOException {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    engine = engineManager.getEngineByName("nashorn");
    if (engine == null) {
      // java 7 fallback
      engine = engineManager.getEngineByName("JavaScript");
    }

    // preload all scripts and dependencies given by the caller
    for (String js : javascriptFilesToLoad) {
      load(engine, js);
    }

    referenceToJavascriptJSONInstance = engine.eval("JSON");
  }
  private Object executeScript(InputStream script, Map<String, Object> params) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine scriptEngine = manager.getEngineByName(engineName);
    scriptEngine.put("engine", engineName);

    Bindings bindings = new SimpleBindings();
    if (params != null && params.size() > 0) {
      for (Map.Entry<String, Object> entry : params.entrySet()) {
        bindings.put(entry.getKey(), entry.getValue());
      }
    }

    // Set default plugins
    for (String plugin : getDefaultPlugins()) {
      Plugin pluginInstance = getPlugin(plugin);
      if (plugin != null) {
        bindings.put(pluginInstance.getName(), pluginInstance);
      }
    }

    Reader reader = new InputStreamReader(script);
    Object result = scriptEngine.eval(reader, bindings);
    reader.close();
    script.close();
    return result;
  }
Пример #5
0
/**
 * Implement {@link ICompressor} using UglifyJS
 *
 * @see <a href="https://github.com/mishoo/UglifyJS2">https://github.com/mishoo/UglifyJS2</a>
 */
public class UglifyJSCompressor implements ICompressor {
  private static Log logger_ = LogFactory.getLog(ICompressor.class);
  private ResourceType type_;
  ScriptEngineManager sem = new ScriptEngineManager();
  ScriptEngine engine = sem.getEngineByName("JavaScript");

  public UglifyJSCompressor(ResourceType type) {
    if (ResourceType.JS != type)
      throw new IllegalArgumentException("UglifyJS compressor does not support CSS compression");
    type_ = type;
  }

  @Override
  public void compress(Reader r, Writer w) throws Exception {
    String script = "function hello(name) { return ('Hello, ' + name); }";
    engine.eval(script);
    Invocable inv = (Invocable) engine;
    inv.invokeFunction("hello", "Scripting!!");
    throw new UnsupportedOperationException();
  }

  public static void main(String[] args) throws Exception {
    new UglifyJSCompressor(ResourceType.JS).compress(null, null);
  }
}
  @Override
  public boolean isActive(FeatureState featureState, FeatureUser user) {

    String lang = featureState.getParameter(PARAM_LANG);
    String script = featureState.getParameter(PARAM_SCRIPT);

    ScriptEngine engine = engineManager.getEngineByName(lang);
    if (engine == null) {
      log.error("Could not find script engine for: " + lang);
      return false;
    }

    engine.put("user", user);
    engine.put("date", new Date());
    try {

      Object result = engine.eval(script);
      if (result instanceof Boolean) {
        return ((Boolean) result).booleanValue();
      }

    } catch (ScriptException e) {
      log.error(
          "Could not evaluate script for feature "
              + featureState.getFeature().name()
              + ": "
              + e.getMessage());
    }
    return false;
  }
Пример #7
0
  @Override
  protected void setUp() throws Exception {
    clearWorkDir();

    FileWriter w = new FileWriter(new File(getWorkDir(), "template.txt"));
    w.write("<html><h1>${title}</h1></html>");
    w.close();

    parameters = new HashMap<String, String>();
    parameters.put("title", "SOME_TITLE");

    LocalFileSystem lfs = new LocalFileSystem();
    lfs.setRootDirectory(getWorkDir());
    fo = lfs.findResource("template.txt");

    ScriptEngineManager mgr = new ScriptEngineManager();
    eng = mgr.getEngineByName("freemarker");
    assertNotNull("We do have such engine", eng);
    eng.getContext().setAttribute(FileObject.class.getName(), fo, ScriptContext.ENGINE_SCOPE);
    eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(parameters);

    whereTo = new File[10000];
    for (int i = 0; i < whereTo.length; i++) {
      whereTo[i] = new File(getWorkDir(), "outFile" + i + ".txt");
    }
  }
  static void nashornCompiledScriptReturningFunction(String code, String library)
      throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    ScriptContext libraryContext = new SimpleScriptContext();
    ScriptContext privateContext = new SimpleScriptContext();

    ScriptObjectMirror errorFunc =
        (ScriptObjectMirror) ((Compilable) engine).compile(library).eval(libraryContext);
    ScriptObjectMirror func =
        (ScriptObjectMirror) ((Compilable) engine).compile(code).eval(privateContext);
    Object result = null;

    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        result = func.call(null, "12345678", errorFunc);
      }
      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 " + result.toString());
  }
  static void nashornInvokeMethod(String code) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");

    engine.eval(code);
    Invocable inv = (Invocable) engine;
    JSObject propertiesDict = (JSObject) engine.get("properties");

    Object result = null;
    Object property;
    long total = 0;
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      for (int j = 0; j < BATCH; ++j) {
        property = propertiesDict.getMember("ssn");
        result = inv.invokeMethod(property, "clean", "12345678");
      }
      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());
  }
Пример #10
0
  /** Test of get method, of class Jsr223JRubyEngine. */
  @Test
  public void testGet() {
    logger1.info("get");
    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");
    }

    instance.put("abc", "aabc");
    instance.put("@abc", "abbc");
    instance.put("$abc", "abcc");
    String key = "abc";
    Object expResult = "aabc";
    Object result = instance.get(key);
    assertEquals(expResult, result);
    List list = new ArrayList();
    list.add("aabc");
    instance.put("abc", list);
    Map map = new HashMap();
    map.put("Ruby", "Rocks");
    instance.put("@abc", map);
    result = instance.get(key);
    assertEquals(expResult, ((List) result).get(0));
    key = "@abc";
    expResult = "Rocks";
    result = instance.get(key);
    assertEquals(expResult, ((Map) result).get("Ruby"));

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #11
0
  public static Object executeScriptFileHeadless(
      ScriptItem scriptItem, boolean forceFromFile, Map<String, Object> additionalBindings) {
    ScriptEngineManager manager = new ScriptEngineManager(ScriptingWindow.class.getClassLoader());
    ScriptEngine scriptEngine =
        manager.getEngineByExtension(getFileExtension(scriptItem.getName()));

    if (scriptEngine == null) {
      scriptEngine = manager.getEngineByName(DEFAULT_SCRIPT);
    }

    SimpleBindings bindings = new SimpleBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_RESOURCES, scriptItem.getResourceBundle());

    if (additionalBindings != null) {
      bindings.putAll(additionalBindings);
    }

    Object eval = null;
    try {
      eval = scriptEngine.eval(scriptItem.getText(), bindings);
      if (eval != null) {
        Log.logRB("SCW_SCRIPT_RESULT");
        Log.log(eval.toString());
      }
    } catch (Throwable e) {
      Log.logErrorRB(e, "SCW_SCRIPT_ERROR");
    }

    return eval;
  }
Пример #12
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_Reader_ScriptContext() throws Exception {
    logger1.info("[eval Reader with ScriptContext]");
    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/list_printer.rb";
    Reader reader = new FileReader(filename);
    ScriptContext context = new SimpleScriptContext();

    String[] big5 = {"Alaska", "Texas", "California", "Montana", "New Mexico"};
    context.setAttribute("@list", Arrays.asList(big5), ScriptContext.ENGINE_SCOPE);
    StringWriter sw = new StringWriter();
    context.setWriter(sw);
    instance.eval(reader, context);
    String expResult = "Alaska >> Texas >> California >> Montana >> New Mexico: 5 in total";
    assertEquals(expResult, sw.toString().trim());

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #13
0
 public void setLanguage(String language) {
   engine = factory.getEngineByName(language);
   if (engine == null) {
     throw new IllegalArgumentException("No puedo encontrar el interprete de [" + language + "]");
   }
   this.language = language;
 }
Пример #14
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;
  }
Пример #15
0
  /** Test of getInterface method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetInterface_Object_Class() throws FileNotFoundException, ScriptException {
    logger1.info("getInterface (with receiver)");
    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/position_function.rb";
    Reader reader = new FileReader(filename);
    Bindings bindings = instance.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("initial_velocity", 30.0);
    bindings.put("initial_height", 30.0);
    bindings.put("system", "metric");
    Object receiver = instance.eval(reader, bindings);
    Class returnType = PositionFunction.class;
    PositionFunction result =
        (PositionFunction) ((Invocable) instance).getInterface(receiver, returnType);
    double expResult = 75.9;
    double t = 3.0;
    assertEquals(expResult, result.getPosition(t), 0.1);

    expResult = 20.2;
    t = 1.0;
    assertEquals(expResult, result.getVelocity(t), 0.1);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #16
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);
  }
Пример #17
0
  @Test
  public void testTermination() throws ScriptException {
    logger1.info("Termination Test");
    ScriptEngineManager manager = new ScriptEngineManager();
    JRubyEngine instance = (JRubyEngine) manager.getEngineByName("jruby");
    instance.eval("$x='GVar'");
    StringWriter sw = new StringWriter();
    instance.getContext().setWriter(sw);
    instance.eval("at_exit { puts \"#{$x} in an at_exit block\" }");
    String expResult = "";
    assertEquals(expResult, sw.toString().trim());

    sw = new StringWriter();
    instance.getContext().setWriter(sw);
    instance
        .getContext()
        .setAttribute("org.jruby.embed.termination", true, ScriptContext.ENGINE_SCOPE);
    instance.eval("");
    expResult = "GVar in an at_exit block";
    assertEquals(expResult, sw.toString().trim());
    instance
        .getContext()
        .setAttribute("org.jruby.embed.termination", false, ScriptContext.ENGINE_SCOPE);
    instance = null;
  }
  /**
   * @param engineName the script engine name (eg "groovy", etc)
   * @return the Script engine to use to evaluate the script
   * @throws MacroExecutionException in case of an error in parsing the jars parameter
   */
  private ScriptEngine getScriptEngine(String engineName) throws MacroExecutionException {
    // Look for a script engine in the Execution Context since we want the same engine to be used
    // for all evals during the same execution lifetime.
    // We must use the same engine because that engine may create an internal ClassLoader in which
    // it loads new classes defined in the script and if we create a new engine then defined classes
    // will be lost.
    // However we also need to be able to execute several script Macros during a single execution
    // request
    // and for example the second macro could have jar parameters. In order to support this use case
    // we ensure in AbstractScriptMacro to reuse the same thread context ClassLoader during the
    // whole
    // request execution.
    ExecutionContext executionContext = this.execution.getContext();
    Map<String, ScriptEngine> scriptEngines =
        (Map<String, ScriptEngine>) executionContext.getProperty(EXECUTION_CONTEXT_ENGINE_KEY);
    if (scriptEngines == null) {
      scriptEngines = new HashMap<String, ScriptEngine>();
      executionContext.setProperty(EXECUTION_CONTEXT_ENGINE_KEY, scriptEngines);
    }
    ScriptEngine engine = scriptEngines.get(engineName);

    if (engine == null) {
      ScriptEngineManager sem = new ScriptEngineManager();
      engine = sem.getEngineByName(engineName);
      scriptEngines.put(engineName, engine);
    }

    return engine;
  }
Пример #19
0
/** Created by Josue on 26/05/2016. */
public class ScriptProcessor implements EntryProcessor<String, Integer, Integer> {

  private final ScriptEngineManager manager = new ScriptEngineManager();
  private final ScriptEngine engine = manager.getEngineByName("JavaScript");
  private final String script;

  private static final Logger log = Logger.getLogger(ScriptProcessor.class.getName());

  public ScriptProcessor(String script) {
    this.script = script;
  }

  @Override
  public Integer process(MutableEntry<String, Integer> mutableEntry, Object... objects)
      throws EntryProcessorException {
    try {
      String finalScript = "function run(value, log) {" + script + "}";

      engine.eval(finalScript);
      Double outputValue =
          (Double)
              ((Invocable) engine)
                  .invokeFunction("run", new Object[] {mutableEntry.getValue(), log});
      int newValue = outputValue.intValue();
      mutableEntry.setValue(newValue);
      return newValue;

    } catch (Exception e) {
      throw new EntryProcessorException("Error executing script", e);
    }
  }
}
Пример #20
0
  @Test
  public void testEngine() {
    ScriptEngineManager m = new ScriptEngineManager();

    Assert.assertNotNull(m.getEngineByExtension("rb"));
    Assert.assertNotNull(m.getEngineByName("ruby"));
  }
Пример #21
0
  @Override
  public void run() {
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine e = scriptEngineManager.getEngineByName("javascript");
    if (map != null) {
      for (Map.Entry<String, ?> entry : map.entrySet()) {
        e.put(entry.getKey(), entry.getValue());
      }
    }
    e.put("hazelcast", hazelcastInstance);
    try {
      // for new JavaScript engine called Nashorn we need the compatibility script
      if (e.getFactory().getEngineName().toLowerCase().contains("nashorn")) {
        e.eval("load('nashorn:mozilla_compat.js');");
      }

      e.eval("importPackage(java.lang);");
      e.eval("importPackage(java.util);");
      e.eval("importPackage(com.hazelcast.core);");
      e.eval("importPackage(com.hazelcast.config);");
      e.eval("importPackage(java.util.concurrent);");
      e.eval("importPackage(org.junit);");
      e.eval(script);
    } catch (ScriptException e1) {
      throw new RuntimeException(e1);
    }
  }
Пример #22
0
 @Test
 public void testClearVariables() throws ScriptException {
   logger1.info("Clear Variables Test");
   ScriptEngine instance = null;
   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");
   }
   instance.put("gvar", ":Gvar");
   String result = (String) instance.eval("$gvar");
   assertEquals(":Gvar", result);
   instance.getBindings(ScriptContext.ENGINE_SCOPE).remove("gvar");
   instance
       .getContext()
       .setAttribute("org.jruby.embed.clear.variables", true, ScriptContext.ENGINE_SCOPE);
   instance.eval("");
   instance
       .getContext()
       .setAttribute("org.jruby.embed.clear.variables", false, ScriptContext.ENGINE_SCOPE);
   result = (String) instance.eval("$gvar");
   assertNull(result);
   instance = null;
 }
Пример #23
0
  public ScriptExecutor(ScriptExecutionRequest request) {
    this.request = request;

    ScriptEngineManager factory = new ScriptEngineManager();
    engine = factory.getEngineByName(request.format);

    engine.put("output", request.output);

    /** */
    if (request.script == null || request.script.equals("") == true) {

      /** Default root is the the resource folder of the current project. */
      String root = "src/main/resources/library/";
      if (System.getProperty("hbird.scriptlibrary") != null) {
        root = System.getProperty("hbird.scriptlibrary");
        if (root.endsWith("/") == false) {
          root += "/";
        }
      }

      File file = new File(root + request.name + ".js");
      if (file.exists() == false) {
        LOG.error("Failed to find script file '" + file.getAbsolutePath() + "'.");
        LOG.error(
            "Use the runtime system property '-Dhbird.scriptlibrary=[path]' to point to the script library. Script will not be evaluated.");
      } else {
        try {
          request.script = FileUtils.readFileToString(file);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Пример #24
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;
  }
Пример #25
0
  /** Test of getInterface method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetInterface_Class() throws FileNotFoundException, ScriptException {
    logger1.info("getInterface (no receiver)");
    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 = (JRubyEngine) manager.getEngineByName("jruby");
    }
    Class returnType = RadioActiveDecay.class;
    String filename = basedir + "/src/test/ruby/org/jruby/embed/ruby/radioactive_decay.rb";
    Reader reader = new FileReader(filename);
    Bindings bindings = instance.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("$h", 5715); // half-life of Carbon
    instance.eval(reader);
    double expResult = 8.857809480593293;
    RadioActiveDecay result = (RadioActiveDecay) ((Invocable) instance).getInterface(returnType);
    assertEquals(expResult, result.amountAfterYears(10.0, 1000), 0.000001);
    expResult = 18984.81906228128;
    assertEquals(expResult, result.yearsToAmount(10.0, 1.0), 0.000001);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #26
0
  /** Test of invokeFunction method, of class Jsr223JRubyEngine. */
  @Test
  public void testInvokeFunction() throws Exception {
    logger1.info("invokeFunction");
    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/count_down.rb";
    Reader reader = new FileReader(filename);
    Bindings bindings = new SimpleBindings();
    bindings.put("@month", 6);
    bindings.put("@day", 3);
    instance.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    Object result = instance.eval(reader, bindings);

    String method = "count_down_birthday";
    bindings.put("@month", 12);
    bindings.put("@day", 3);
    instance.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    Object[] args = null;
    result = ((Invocable) instance).invokeFunction(method, args);
    assertTrue(((String) result).startsWith("Happy") || ((String) result).startsWith("You have"));

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Пример #27
0
  @Before
  public void setUp() {
    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();

    engine = factory.getEngineByName("Renjin");
    invocableEngine = (Invocable) engine;
  }
 @BeforeClass
 public static void setUpClass() throws ScriptException {
   final ScriptEngineManager m = new ScriptEngineManager();
   e = m.getEngineByName("nashorn");
   o = new SharedObject();
   e.put("o", o);
   e.eval("var SharedObject = Packages.jdk.nashorn.api.javaaccess.SharedObject;");
 }
 /**
  * Overrides default behavior of aggregation with the one programmed in script
  *
  * @param scripting script definition
  */
 public void initCustomAggregation(Scripting scripting) {
   ScriptEngineManager factory = new ScriptEngineManager();
   scriptEngine = factory.getEngineByName(scripting.getLanguage());
   Preconditions.checkNotNull(
       scriptEngine, "ScriptEngine for language {} was not found.", scripting.getLanguage());
   script = scripting.getScript();
   LOG.debug("Next script will be used for custom aggregation: {}", script);
 }
 public ScriptRewardMatcher(Path path) throws IOException, ScriptException {
   this.path = path;
   ScriptEngineManager manager = new ScriptEngineManager();
   engine = manager.getEngineByName("JavaScript");
   try (Reader reader = Files.newBufferedReader(path)) {
     engine.eval(reader);
   }
 }