Пример #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;
  }
 @Test
 public void accessStaticFinalFieldStringArray() throws ScriptException {
   e.eval("var psf_string_array = SharedObject.publicStaticFinalStringArray;");
   assertEquals(
       SharedObject.publicStaticFinalStringArray[0],
       e.eval("SharedObject.publicStaticFinalStringArray[0]"));
   assertArrayEquals(
       SharedObject.publicStaticFinalStringArray, (String[]) e.get("psf_string_array"));
   e.eval(
       "var tsf_string_arr = new (Java.type(\"java.lang.String[]\"))(3);"
           + "tsf_string_arr[0] = 'abc';"
           + "tsf_string_arr[1] = '123';"
           + "tsf_string_arr[2] = 'xyzzzz';"
           + "SharedObject.publicStaticFinalStringArray = tsf_string_arr;");
   assertArrayEquals(
       new String[] {
         "StaticFinalArrayString[0]",
         "StaticFinalArrayString[1]",
         "StaticFinalArrayString[2]",
         "StaticFinalArrayString[3]"
       },
       SharedObject.publicStaticFinalStringArray);
   e.eval("SharedObject.publicStaticFinalStringArray[0] = 'nashorn';");
   assertEquals("nashorn", SharedObject.publicStaticFinalStringArray[0]);
 }
Пример #3
0
 // This code worked successfully on command-line but never as JUnit test
 // <script>:1: undefined method `+' for nil:NilClass (NoMethodError)
 // raised at "Object obj1 = engine1.eval("$Value + 2010.to_s");"
 // @Test
 public void testMultipleEngineStates() throws ScriptException {
   logger1.info("Multiple Engine States");
   ScriptEngine engine1;
   ScriptEngine engine2;
   synchronized (this) {
     System.setProperty("org.jruby.embed.localcontext.scope", "singlethread");
     System.setProperty("org.jruby.embed.localvariable.behavior", "global");
     ScriptEngineManager manager = new ScriptEngineManager();
     List<ScriptEngineFactory> factories = manager.getEngineFactories();
     ScriptEngineFactory factory = null;
     while (factories.iterator().hasNext()) {
       factory = factories.iterator().next();
       if ("ruby".equals(factory.getLanguageName())) {
         break;
       }
     }
     engine1 = factory.getScriptEngine();
     engine2 = factory.getScriptEngine();
   }
   engine1.put("Value", "value of the first engine");
   engine2.put("Value", new Double(-0.0149));
   Object obj1 = engine1.eval("$Value + 2010.to_s");
   Object obj2 = engine2.eval("$Value + 2010");
   assertNotSame(obj1, obj2);
   engine1 = null;
   engine2 = null;
 }
Пример #4
0
  public static void main(String[] args) throws NoSuchMethodException, ScriptException {
    PropertyConfigurator.configure("./log4j.properties");

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("org.postgresql.Driver");

    bds.setUrl("jdbc:postgresql://localhost:5432/booktown");

    bds.setUsername("postgres");
    bds.setPassword("pass4postgres");

    ScriptEngine engine = JsEngineUtil.newEngine();
    engine.put("logger", logger);
    engine.put("dataSource", bds);
    try {
      JsEngineUtil.eval(engine, "web/WEB-INF/jslib/lang.js", true, false);
      JsEngineUtil.eval(engine, "web/WEB-INF/jslib/db2js.js", true, false);
      JsEngineUtil.eval(engine, "test/test_query.js", true, false);
    } catch (Exception e) {
      logger.error("", e);
    }

    Invocable inv = (Invocable) engine;
    inv.invokeMethod(engine.eval("dbjs"), "test1");

    inv.invokeMethod(engine.eval("dbjs"), "travelTest");

    inv.invokeMethod(engine.eval("dbjs"), "paging");

    //		inv.invokeMethod(engine.eval("dbjs"), "insertJson");
    //
    //		inv.invokeMethod(engine.eval("dbjs"), "queryJson");

  }
Пример #5
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;
 }
Пример #6
0
 @Test
 public void shouldRunJavaScript() throws ScriptException, FileNotFoundException {
   ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
   engine.eval("function p(s) { print(s) }");
   engine.eval("p('Hello Nashorn');");
   engine.eval(new FileReader("/home/vijayrc/projs/VRC5/scribbles/java8/js/sample.js"));
 }
  public void testMethodIndirection() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();
    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null);

    Bindings bindings = engine.createBindings();
    Tester tester = new Tester();
    bindings.put("tester", tester);

    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    engine.eval("tester.increment()");

    Assert.assertEquals(tester.getInvocationCoung(), 1, "Unexpected number of tester invocations.");

    Map<String, Set<Method>> methods = getMethodsByName(Tester.class);
    for (Set<Method> ms : methods.values()) {
      Set<String> fns = initializer.generateIndirectionMethods("tester", ms);
      for (String fn : fns) {
        engine.eval(fn);
      }
    }

    engine.eval("increment()");
    Assert.assertEquals(
        tester.getInvocationCoung(),
        2,
        "Unexpected number of tester invocations after calling an indirected method.");
  }
 @Test
 public void testDefinition() throws ScriptException {
   frege.eval("f x y = x + y");
   final Object actual = frege.eval("f 3 4");
   final Object expected = 7;
   assertEquals(expected, actual);
 }
Пример #9
0
  /** Initialize. */
  private void initialize() {
    try {
      switch (scriptType) {
        case JAVASCRIPT:
          jsEngine.eval(jsBase + script);
          break;
          // TODO fix ruby scripts breaking on windows
        case RUBY:
          rbEngine.eval(rbBase + script);
          break;
      }
    } catch (ScriptException e) {

      new NSAlertBox(
          "Script Read Error",
          reference.getName()
              + " has an error. Due to error reporting methods, I can not help you narrow down the issue. Here is a stack trace:\n"
              + e.getMessage(),
          SWT.ICON_ERROR);

      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error(
          "Script initialization failed: "
              + reference.getName()
              + " at line #"
              + e.getLineNumber());
    } catch (Exception e) {
      org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scripts");
      fLog.error("Script initialization failed: " + e.getStackTrace());
    }
  }
 @Test
 public void testTickInName() throws ScriptException {
   frege.eval("conanOBrien' = \"It's a-me, Conan O'Brien!\"");
   final Object actual = frege.eval("conanOBrien'");
   final Object expected = "It's a-me, Conan O'Brien!";
   assertEquals(expected, actual);
 }
Пример #11
0
  public static void main(String[] args) throws ScriptException, IOException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval("print('Hello Nashorn!');");
    try (InputStream envStream = LessRunner.class.getResourceAsStream("less-env-2.5.3.js");
        InputStream lessStream = LessRunner.class.getResourceAsStream("less-2.5.3.js")) {

      engine.eval(new InputStreamReader(envStream));
      engine.eval(new InputStreamReader(lessStream));
      String runner =
          "var less = createFromEnvironment(lessenv);\n"
              + "less.render('.class { width: (1 + 1) }',\n"
              + "{\n"
              + "paths: ['.', './lib'],\n"
              + // Specify search paths for @import directives
              "filename: 'style.less',\n"
              + // Specify a filename, for better error messages
              "compress: true\n"
              + // Minify CSS output
              "},\n"
              + "function (e, output) {\n"
              + "print(output.css);\n"
              + "});\n";
      engine.eval(runner);
    }
  }
 @Test
 public void testDefinitionWithTypeAnn() throws ScriptException {
   frege.eval("f :: Int -> Int -> Int\n" + "f x y = x + y");
   frege.eval("g :: Int -> Int -> Int\n" + "g x y = x + y");
   final Object actual = frege.eval("f 3 4");
   final Object expected = 7;
   assertEquals(expected, actual);
 }
 @Test
 public void testImportOperators() throws ScriptException {
   frege.eval("import Data.Monoid");
   frege.eval("import frege.data.wrapper.Num");
   final Object actual = frege.eval("Sum.unwrap $ Sum 1 <> Sum 0");
   final Object expected = 1;
   assertEquals(expected, actual);
 }
 @Test
 public void testOperators() throws ScriptException {
   frege.eval("infix 1 `³`");
   frege.eval("(x³) = x^3");
   final Object actual = frege.eval("(2³)");
   final Object expected = 8;
   assertEquals(expected, actual);
 }
 @Test
 public void testUnpackagedModule() throws ScriptException {
   frege.eval("module Bar where { bar = \"I am bar\"}");
   frege.eval("pure native bar Bar.bar :: String");
   final Object actual = frege.eval("bar");
   final Object expected = "I am bar";
   assertEquals(expected, actual);
 }
 @Test
 public void accessFieldString() throws ScriptException {
   e.eval("var p_string = o.publicString;");
   assertEquals(o.publicString, e.get("p_string"));
   assertEquals("string", e.eval("typeof p_string;"));
   e.eval("o.publicString = 'changedString';");
   assertEquals("changedString", o.publicString);
 }
Пример #17
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);
 }
 @Test
 public void accessStaticFieldString() throws ScriptException {
   e.eval("var ps_string = SharedObject.publicStaticString;");
   assertEquals(SharedObject.publicStaticString, e.get("ps_string"));
   assertEquals("string", e.eval("typeof ps_string;"));
   e.eval("SharedObject.publicStaticString = 'changedString';");
   assertEquals("changedString", SharedObject.publicStaticString);
 }
  @Test
  public void putNullRef() throws ScriptException {

    engine.put("x", 42);
    assertThat(engine.eval("x == 42"), CoreMatchers.<Object>equalTo(LogicalVector.TRUE));

    engine.put("x", null);
    assertThat(engine.eval("is.null(x)"), CoreMatchers.<Object>equalTo(LogicalVector.TRUE));
  }
 @Test
 public void testInlineDefinitionWithTypeAnn() throws ScriptException {
   frege.eval("type F = (forall b. [b] -> [b]) -> Int");
   frege.eval("g :: F -> Int; g f = f reverse");
   frege.eval("k2 (f :: [Int] -> [Int]) = 42");
   final Object expected = frege.eval("g k2");
   final Object actual = 42;
   assertEquals(expected, actual);
 }
 @Test
 public void testModule() throws ScriptException {
   frege.eval("module foo.Foo where { bar = \"I am bar from foo\"}");
   frege.eval("import foo.Foo");
   frege.eval("baz = bar");
   final Object actual = frege.eval("baz");
   final Object expected = "I am bar from foo";
   assertEquals(expected, actual);
 }
Пример #22
0
 public static void importClass(ScriptEngine e, Class<?> pkg, Bindings... b) {
   try {
     if (b.length == 0) {
       e.eval("importClass(Packages." + pkg.getName() + ")");
     } else {
       e.eval("importClass(Packages." + pkg.getName() + ")", b[0]);
     }
   } catch (ScriptException e1) {
     throw new RuntimeException(e1);
   }
 }
Пример #23
0
 public Agent() {
   try {
     ScriptEngineManager factory = new ScriptEngineManager();
     engine = factory.getEngineByName("JavaScript");
     engine.eval(new InputStreamReader(getClass().getResourceAsStream("pieces.js")));
     engine.eval(new InputStreamReader(getClass().getResourceAsStream("features.js")));
     engine.eval(new InputStreamReader(getClass().getResourceAsStream("eltetris.js")));
     engine.eval(new InputStreamReader(getClass().getResourceAsStream("game_html.js")));
   } catch (ScriptException ex) {
     Logger.getLogger(Agent.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
 @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);
 }
Пример #25
0
  @Test
  public void serviceShouldBeDeclared() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine =
        engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);

    InputStream stream = this.getClass().getResourceAsStream("/checkWrapper.js");
    assertNotNull(stream);
    engine.eval(scriptingService.getJSWrapper());
    engine.eval(IOUtils.toString(stream));
    assertEquals("Hello" + System.lineSeparator(), outContent.toString());
  }
 @Test
 public void codeCacheTestOpt() throws ScriptException, IOException {
   System.setProperty("nashorn.persistent.code.cache", codeCache);
   final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
   final ScriptEngine e = fac.getScriptEngine(ENGINE_OPTIONS_OPT);
   final Path codeCachePath = getCodeCachePath(true);
   e.eval(code1);
   e.eval(code2);
   e.eval(code3); // less than minimum size for storing
   // adding code1 and code2.
   final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
   checkCompiledScripts(stream, 4);
 }
Пример #27
0
  public CoffeeProcessor() {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    invoker = (Invocable) engine;

    InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("coffee-script.js");
    try {
      engine.eval(new InputStreamReader(stream));
      log.info("CoffeeScript Compiler v{} loaded", engine.eval("CoffeeScript.VERSION"));
      coffee = engine.eval("CoffeeScript");
    } catch (ScriptException e) {
      log.error("Unable to create Coffee compiler", e);
    }
  }
 @Test
 public void testModuleWithComment() throws ScriptException {
   frege.eval(
       "module foo.Foo where\n"
           + "\n"
           + "{--asdfasdf\n"
           + "sadfasdfsadf-}\n"
           + "\n"
           + "baz = \"I am foo!\"");
   frege.eval("import foo.Foo");
   final Object actual = frege.eval("baz");
   final Object expected = "I am foo!";
   assertEquals(expected, actual);
 }
 @Test
 public void accessFieldStringArray() throws ScriptException {
   e.eval("var p_string_array = o.publicStringArray;");
   assertEquals(o.publicStringArray[0], e.eval("o.publicStringArray[0]"));
   assertArrayEquals(o.publicStringArray, (String[]) e.get("p_string_array"));
   e.eval(
       "var t_string_arr = new (Java.type(\"java.lang.String[]\"))(3);"
           + "t_string_arr[0] = 'abc';"
           + "t_string_arr[1] = '123';"
           + "t_string_arr[2] = 'xyzzzz';"
           + "o.publicStringArray = t_string_arr;");
   assertArrayEquals(new String[] {"abc", "123", "xyzzzz"}, o.publicStringArray);
   e.eval("o.publicStringArray[0] = 'nashorn';");
   assertEquals("nashorn", o.publicStringArray[0]);
 }
Пример #30
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;
  }