Beispiel #1
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;
  }
Beispiel #2
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;
  }
Beispiel #3
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;
  }
Beispiel #4
0
  /** Test of createBindings method, of class Jsr223JRubyEngine. */
  @Test
  public void testCreateBindings() {
    logger1.info("createBindings");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine instance = manager.getEngineByName("jruby");
    Bindings bindings = instance.getBindings(ScriptContext.ENGINE_SCOPE);
    Bindings result = instance.createBindings();
    assertNotSame(bindings, result);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #5
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 #6
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;
  }
Beispiel #7
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;
  }
  @Test
  public void putNullRefOnBindings() throws ScriptException {
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

    bindings.put("x", null);
    assertThat(engine.eval("is.null(x)"), CoreMatchers.<Object>equalTo(LogicalVector.TRUE));
  }
Beispiel #9
0
  /**
   * Execute the script and return the ScriptResult corresponding. This method can add an additional
   * user bindings if needed.
   *
   * @param aBindings the additional user bindings to add if needed. Can be null or empty.
   * @param outputSink where the script output is printed to.
   * @param errorSink where the script error stream is printed to.
   * @return a ScriptResult object.
   */
  public ScriptResult<E> execute(
      Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) {
    ScriptEngine engine = createScriptEngine();

    if (engine == null)
      return new ScriptResult<>(
          new Exception("No Script Engine Found for name or extension " + scriptEngineLookup));

    // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE)
    BoundedStringWriter outputBoundedWriter =
        new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE);
    BoundedStringWriter errorBoundedWriter =
        new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE);
    engine.getContext().setWriter(new PrintWriter(outputBoundedWriter));
    engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter));
    Reader closedInput =
        new Reader() {
          @Override
          public int read(char[] cbuf, int off, int len) throws IOException {
            throw new IOException("closed");
          }

          @Override
          public void close() throws IOException {}
        };
    engine.getContext().setReader(closedInput);
    engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE);

    try {
      Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
      // add additional bindings
      if (aBindings != null) {
        for (Entry<String, Object> e : aBindings.entrySet()) {
          bindings.put(e.getKey(), e.getValue());
        }
      }
      prepareBindings(bindings);
      Object evalResult = engine.eval(getReader());

      engine.getContext().getErrorWriter().flush();
      engine.getContext().getWriter().flush();

      // Add output to the script result
      ScriptResult<E> result = this.getResult(evalResult, bindings);
      result.setOutput(outputBoundedWriter.toString());

      return result;
    } catch (javax.script.ScriptException e) {
      // drop exception cause as it might not be serializable
      ScriptException scriptException = new ScriptException(e.getMessage());
      scriptException.setStackTrace(e.getStackTrace());
      return new ScriptResult<>(scriptException);
    } catch (Throwable t) {
      String stack = Throwables.getStackTraceAsString(t);
      if (t.getMessage() != null) {
        stack = t.getMessage() + System.lineSeparator() + stack;
      }
      return new ScriptResult<>(new Exception(stack));
    }
  }
Beispiel #10
0
  public static String bindParameters(
      final ScriptEngine iEngine,
      final Map<Object, Object> iParameters,
      Map<Object, Object> iCurrentParameters) {
    if (iParameters != null && !iParameters.isEmpty())
      // Every call to the function is a execution itself. Therefore, it requires a fresh set of
      // input parameters.
      // Therefore, clone the parameters map trying to recycle previous instances
      for (Entry<Object, Object> param : iParameters.entrySet()) {
        final String key = (String) param.getKey();
        final Object objectToClone = param.getValue();
        final Object previousItem = iCurrentParameters.get(key); // try to recycle it
        final Object newItem = OGremlinHelper.cloneObject(objectToClone, previousItem);
        iCurrentParameters.put(key, newItem);
      }

    String output = null;
    if (iCurrentParameters != null)
      for (Entry<Object, Object> param : iCurrentParameters.entrySet()) {
        final String paramName = param.getKey().toString().trim();
        if (paramName.equals(PARAM_OUTPUT)) {
          output = param.getValue().toString();
          continue;
        }
        iEngine.getBindings(ScriptContext.ENGINE_SCOPE).put(paramName, param.getValue());
      }
    return output;
  }
Beispiel #11
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;
  }
Beispiel #12
0
  /**
   * Invokes a function defined in the script.
   *
   * @param funcName The function name.
   * @param params The parameter array.
   * @return A boolean value representing whether the function is executed correctly. If the
   *     function cannot be found, or parameters don't match, {@code false} is returned.
   */
  public boolean invokeFunction(String funcName, Object[] params) {
    // Run script if it is dirty. This makes sure the script is run
    // on the same thread as the caller (suppose the caller is always
    // calling from the same thread).
    checkDirty();

    String statement = getInvokeStatement(funcName, params);

    Bindings localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    if (localBindings == null) {
      localBindings = mLocalEngine.createBindings();
      mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);
    }

    fillBindings(localBindings, params);

    try {
      mLocalEngine.eval(statement);
    } catch (ScriptException e) {
      return false;
    } finally {
      removeBindings(localBindings, params);
    }

    return true;
  }
Beispiel #13
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;
 }
Beispiel #14
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;
  }
  /**
   * Method to evaluate whether all required input parameters have been set.
   *
   * @return True if all input parameters have been bound to the engine. Else false.
   */
  protected boolean ready() {
    for (String parameter : request.inputBinding.values()) {
      if (engine.getBindings(ScriptContext.ENGINE_SCOPE).containsKey(parameter) == false) {
        LOG.debug("Script '" + request.name + "' Still missing dependency '" + parameter + "'.");
        return false;
      }
    }

    return true;
  }
Beispiel #16
0
  /** Test of getContext method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetContext() {
    logger1.info("getContext");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine instance = manager.getEngineByName("jruby");
    ScriptContext result = instance.getContext();
    assertNotNull(result);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
 @Test
 public void testRebinding() throws ScriptException {
   Bindings bindings = frege.getBindings(ENGINE_SCOPE);
   bindings.put("bar :: Integer", new BigInteger("12312332142343244"));
   final Object actual1 = frege.eval("bar + 3.big");
   final Object expected1 = new BigInteger("12312332142343247");
   bindings.put("bar :: String", "hello ");
   final Object actual2 = frege.eval("bar ++ \"world\"");
   final Object expected2 = "hello world";
   assertEquals(expected1, actual1);
   assertEquals(expected2, actual2);
 }
Beispiel #18
0
  /** Test of getFactory method, of class Jsr223JRubyEngine. */
  @Test
  public void testGetFactory() {
    logger1.info("getFactory");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine instance = manager.getEngineByName("jruby");
    ScriptEngineFactory result = instance.getFactory();
    assertTrue(result instanceof JRubyEngineFactory);
    String expResult = "JSR 223 JRuby Engine";
    String ret = result.getEngineName();
    assertEquals(expResult, ret);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #19
0
  /** Test of put method, of class Jsr223JRubyEngine. */
  @Test
  public void testPut() {
    logger1.info("put");
    String key = "";
    Object value = null;
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine instance = manager.getEngineByName("jruby");
    try {
      instance.put(key, value);
    } catch (IllegalArgumentException e) {
      String expResult = "key can not be empty";
      assertEquals(expResult, e.getMessage());
    }

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #20
0
  /** Test of setContext method, of class Jsr223JRubyEngine. */
  @Test
  public void testSetContext() {
    logger1.info("setContext");
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine instance = manager.getEngineByName("jruby");
    ScriptContext ctx = new SimpleScriptContext();
    StringWriter sw = new StringWriter();
    sw.write("Have a great summer!");
    ctx.setWriter(sw);
    instance.setContext(ctx);
    ScriptContext result = instance.getContext();
    Writer w = result.getWriter();
    Object expResult = "Have a great summer!";
    assertTrue(sw == result.getWriter());
    assertEquals(expResult, (result.getWriter()).toString());

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
  public Gauge getGauge(InputStream stream) {
    GeneralPath path = new GeneralPath();
    GaugeFactoryAPI api = new GaugeFactoryAPI();

    InputStreamReader reader = new InputStreamReader(stream);

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("path", path);
    bindings.put("self", api);
    try {
      engine.eval(reader, bindings);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Gauge gauge = new Gauge(path, api.color);
    return gauge;
  }
Beispiel #22
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_Reader() throws Exception {
    logger1.info("eval Reader");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.class.path", basedir + "/lib/ruby/1.9");
      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 filename = basedir + "/src/test/ruby/org/jruby/embed/ruby/next_year.rb";
    Reader reader = new FileReader(filename);

    long expResult = getNextYear();
    Object result = instance.eval(reader);
    assertEquals(expResult, result);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #23
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_String() throws Exception {
    logger1.info("eval String");
    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.getContext().setWriter(writer);
    instance.eval("p=9.0");
    instance.eval("q = Math.sqrt p");
    instance.eval("puts \"square root of #{p} is #{q}\"");
    Double expResult = 3.0;
    Double result = (Double) instance.get("q");
    assertEquals(expResult, result, 0.01);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #24
0
  /** Test of setBindings method, of class Jsr223JRubyEngine. */
  @Test
  public void testSetBindings() throws ScriptException {
    logger1.info("setBindings");
    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 script = "def message\n" + "\"message: #{@message}\"\n" + "end\n" + "message";
    Bindings bindings = new SimpleBindings();
    bindings.put("@message", "What's up?");
    int scope = ScriptContext.ENGINE_SCOPE;
    Object expResult = "message: What's up?";
    instance.setBindings(bindings, scope);
    Object result = instance.eval(script);
    assertEquals(expResult, result);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #25
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_String_ScriptContext() throws Exception {
    logger1.info("[eval String with ScriptContext]");
    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(1, 3)";
    ScriptContext context = new SimpleScriptContext();
    List<Double> expResult = new ArrayList();
    expResult.add(3.392);
    expResult.add(8.571);
    List<Double> result = (List<Double>) instance.eval(script, context);
    for (int i = 0; i < result.size(); i++) {
      assertEquals(expResult.get(i), result.get(i), 0.01);
    }

    script = "def get_area\n" + "$x * $y + Math::PI / 8.0 * $x ** 2.0\n" + "end\n" + "get_area";
    context.setAttribute("x", 1.0, ScriptContext.ENGINE_SCOPE);
    context.setAttribute("y", 3.0, ScriptContext.ENGINE_SCOPE);
    Double result2 = (Double) instance.eval(script, context);
    assertEquals(expResult.get(0), result2, 0.01);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #26
0
  /**
   * Выполняет скрипт
   *
   * @param script Тело скрипта / код
   * @param language Язык скрипта (JavaScript)
   * @param bindings Переменные для привязки/передачи данных
   * @return Результат выполнения
   * @throws ScriptException Ошибка исполнения скрипта
   */
  public static Object eval(
      String script, String language, Map<? extends String, ? extends Object> bindings)
      throws ScriptException {
    if (script == null) throw new IllegalArgumentException("script==null");
    if (language == null) throw new IllegalArgumentException("language==null");
    //        if( bindings==null )throw new IllegalArgumentException("bindings==null");

    ScriptEngine se = null;
    Map<String, ScriptEngine> map = getMapScriptEngines();
    if (map.containsKey(language)) {
      se = map.get(language);
    } else {
      se = getScriptEngineManager().getEngineByName(language);
      if (se == null)
        throw new IllegalArgumentException(Text.template("language ({0}) not supported", language));
      map.put(language, se);
    }

    Bindings seBindings = se.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
    if (bindings != null) seBindings.putAll(bindings);

    return se.eval(script);
  }
Beispiel #27
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_Reader_Bindings() throws Exception {
    logger1.info("eval Reader with Bindings");
    ScriptEngine instance;
    synchronized (this) {
      System.setProperty("org.jruby.embed.class.path", basedir + "/lib/ruby/1.9");
      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", 2);
    instance.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    String result = (String) instance.eval(reader, bindings);
    assertTrue(result.startsWith("Happy") || result.startsWith("You have"));

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
Beispiel #28
0
  /** Test of eval method, of class Jsr223JRubyEngine. */
  @Test
  public void testEval_String_ScriptContext2() throws Exception {
    logger1.info("[eval String with ScriptContext 2]");
    ScriptEngine instance = null;
    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");
    }
    ScriptContext context = new SimpleScriptContext();

    String script =
        "def get_area\n" + "@x * @y + Math::PI / 8.0 * @x ** 2.0\n" + "end\n" + "get_area";
    context.setAttribute("@x", 1.0, ScriptContext.ENGINE_SCOPE);
    context.setAttribute("@y", 3.0, ScriptContext.ENGINE_SCOPE);
    Double expResult = 3.392;
    Double result = (Double) instance.eval(script, context);
    assertEquals(expResult, result, 0.01);

    instance.getBindings(ScriptContext.ENGINE_SCOPE).clear();
    instance = null;
  }
  @Override
  public void execute(String line, PrintStream out, PrintStream err) {
    if (scriptEngine == null) {
      err.println(
          "Frege ScriptEngine not found!\n"
              + "Make sure to make the Frege jar available in the classpath before trying to use it.\n"
              + "If you use the osgi-run Gradle plugin, add frege-interpreter-core as a systemLib dependency.");
    } else {
      Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);

      bindings.put("out", out);
      bindings.put("err", err);
      bindings.put("ctx", bundleContext);

      try {
        @Nullable Object result = scriptEngine.eval(line.substring(getName().length() + 1));
        if (result != null) {
          out.println(result);
        }
      } catch (Throwable e) {
        err.println(e.toString());
      }
    }
  }
Beispiel #30
0
  /**
   * Invokes a function defined in the script.
   *
   * @param funcName The function name.
   * @param params The parameter array.
   * @return A boolean value representing whether the function is executed correctly. If the
   *     function cannot be found, or parameters don't match, {@code false} is returned.
   */
  public boolean invokeFunction(String funcName, Object[] params) {
    // Run script if it is dirty. This makes sure the script is run
    // on the same thread as the caller (suppose the caller is always
    // calling from the same thread).
    checkDirty();

    // Skip bad functions
    if (isBadFunction(funcName)) {
      return false;
    }

    String statement = getInvokeStatementCached(funcName, params);

    Bindings localBindings = null;
    synchronized (mEngineLock) {
      localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE);
      if (localBindings == null) {
        localBindings = mLocalEngine.createBindings();
        mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE);
      }
    }

    fillBindings(localBindings, params);

    try {
      mLocalEngine.eval(statement);
    } catch (ScriptException e) {
      // The function is either undefined or throws, avoid invoking it later
      addBadFunction(funcName);
      return false;
    } finally {
      removeBindings(localBindings, params);
    }

    return true;
  }