@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);
 }
 @Test
 public void putPrimitiveLongArray() throws ScriptException {
   long[] longs = new long[] {1, 2, 3, 4, 5};
   engine.put("longs", longs);
   IntArrayVector lav = (IntArrayVector) engine.eval("as.integer(longs)");
   assertThat(lav.length(), equalTo(5));
 }
  @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));
  }
  @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);
    }
  }
Example #5
0
 public void reloadScript() {
   onDisable();
   try {
     ScriptEngine engine = ((ScriptLoader) loader).getScriptEngine(file);
     engine.put(Utils.getStringOrDefault(engine, "HELPER_VARIABLE_NAME", "helper"), helper);
     engine.put(Utils.getStringOrDefault(engine, "PLUGIN_VARIABLE_NAME", "plugin"), this);
     engine.put(Utils.getStringOrDefault(engine, "SERVER_VARIABLE_NAME", "server"), server);
     sEngine = (Invocable) engine;
   } catch (FileNotFoundException fnfe) {
     log(
         Level.SEVERE,
         String.format(
             "Not reloading script \"%s\"; file not found. Was the script file moved or deleted?",
             file.getName()),
         fnfe);
   } catch (ScriptException sex) {
     log(
         Level.SEVERE,
         String.format("Not reloading script \"%s\"; error while parsing script.", file.getName()),
         sex);
   } catch (InvalidPluginException ipe) {
     log(
         Level.SEVERE,
         String.format(
             "Not reloading script \"%s\"; someone broke jxpl via reflection.", file.getName()),
         ipe);
   } finally {
     onEnable();
   }
 }
Example #6
0
  private synchronized ScriptEngineState getEngineByName(String name, boolean reset)
      throws SoarException {
    ScriptEngineState state = engines.get(name);
    if (state != null && reset) {
      state.dispose();
      engines.remove(name);
      state = null;
    }

    if (state == null) {
      final ScriptEngine engine = getEngineManager().getEngineByName(name);
      if (engine == null) {
        throw new SoarException("Unsupported script engine '" + name + "'");
      }

      final ScriptEngineFactory f = engine.getFactory();
      logger.info(
          String.format(
              "Loaded '%s' script engine for %s: %s version %s, %s version %s",
              name,
              context,
              f.getEngineName(),
              f.getEngineVersion(),
              f.getLanguageName(),
              f.getLanguageVersion()));

      engines.put(name, state = new ScriptEngineState(context, name, engine));
    }
    return state;
  }
  public void testEngineInitialization() throws Exception {
    PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer();
    ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null);

    // just some code to test out this is python
    engine.eval("from java.util import HashMap\nHashMap()");
  }
Example #8
0
  @SuppressWarnings({"null", "unchecked"})
  @Override
  public Object call(
      Object o,
      Object o2,
      Object o3,
      Object o4,
      Object o5,
      Object o6,
      Object o7,
      Object o8,
      Object o9,
      Object o10,
      Object o11)
      throws Exception {
    ScriptEngine e = NashornEngineSingleton.getEngine();
    if (this.fn == null) {
      this.fn = e.eval(func);
    }
    Invocable invocable = (Invocable) e;

    Object params[] = {this.fn, o, o2, o3, o4, o5, o6, o7, o8, o9, o10, o11};

    if (this.args != null && this.args.length > 0) {
      params = ArrayUtils.addAll(params, this.args);
    }

    Object ret = invocable.invokeFunction("Utils_invoke", params);
    ret = this.castValueToReturnType(ret);
    return ret;
  }
  @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;
  }
Example #10
0
 /**
  * Loads a module.
  *
  * @param moduleName
  * @return
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws ClassNotFoundException
  * @throws IOException
  * @throws ScriptException
  * @throws NoSuchMethodException
  * @throws NoClassDefFoundError
  * @throws ClassCastException
  */
 public Module load(String moduleName)
     throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException,
         NoSuchMethodException, ScriptException {
   if (moduleName.contains(".")) {
     // if the name has a dot, assume a script
     System.out.print("Loading Module " + moduleName + " ... ");
     File file = new File(scriptDir(moduleName) + File.separatorChar + moduleName);
     BufferedReader bis = new BufferedReader(new FileReader(file));
     String line;
     String script = "";
     while ((line = bis.readLine()) != null) {
       script += line + "\n";
     }
     String extension = moduleName.replaceAll(".*\\.", "");
     ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(extension);
     engine.eval(script);
     Invocable inv = (Invocable) engine;
     Module mod;
     Object moduleCandidate = inv.invokeFunction("getInstance");
     if (moduleCandidate instanceof Module) {
       mod = (Module) moduleCandidate;
     } else {
       mod = new JSR223Module(extension, script);
     }
     mod.moduleName = moduleName;
     bootModule(mod);
     return mod;
   } else {
     moduleName = "goat.module." + moduleName;
     return load(Class.forName(moduleName));
   }
 }
  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());
  }
 @Test
 public void testBindingWithTypeAnn() throws ScriptException {
   frege.put("foo::String", "I am foo");
   final Object actual = frege.eval("\"Hello World, \" ++ foo");
   final Object expected = "Hello World, I am foo";
   assertEquals(expected, actual);
 }
 @Test
 public void testBinding() throws ScriptException {
   frege.put("bar :: Integer", new BigInteger("12312332142343244"));
   final Object actual = frege.eval("bar + 3.big");
   final Object expected = new BigInteger("12312332142343247");
   assertEquals(expected, actual);
 }
 @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);
 }
Example #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;
  }
  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;
  }
Example #17
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"));
 }
 @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]);
 }
Example #19
0
  @Override
  protected ScriptEngine makeEngine() {

    try {
      Class<?> c;
      c = this.getClass().getClassLoader().loadClass("com.sun.script.java.JavaScriptEngineFactory");
      ScriptEngineFactory fact = (ScriptEngineFactory) c.newInstance();

      ScriptEngine engine = fact.getScriptEngine();

      engine
          .getContext()
          .setAttribute(
              "com.sun.script.java.parentLoader",
              Trampoline2.trampoline.getClassLoader(),
              ScriptContext.ENGINE_SCOPE);
      engine
          .getContext()
          .setAttribute(
              "parentLoader", Trampoline2.trampoline.getClassLoader(), ScriptContext.ENGINE_SCOPE);
      return engine;

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    return null;
  }
Example #20
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;
  }
  private ScriptEngine createEngine(
      String scriptName, String templateName, boolean runInit, Object it, AbstractBuild<?, ?> build)
      throws FileNotFoundException, IOException {
    String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1);

    ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
    if (engine != null) {
      ScriptContext context = engine.getContext();
      context.setAttribute("it", it, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("build", build, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("project", build.getParent(), ScriptContext.GLOBAL_SCOPE);
      context.setAttribute(
          "rooturl", ExtendedEmailPublisher.DESCRIPTOR.getHudsonUrl(), ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("host", this, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("template", templateName, ScriptContext.GLOBAL_SCOPE);

      if (runInit) {
        InputStream initFile = null;
        try {
          initFile = getFileInputStream(extension + "/init." + extension);
          if (initFile != null) {
            engine.eval(new InputStreamReader(initFile));
          }
        } catch (ScriptException e) {
          LOGGER.log(Level.SEVERE, "ScriptException on init file: " + e.toString());
        } catch (Exception e) {
          LOGGER.log(Level.SEVERE, "Exception on init file: " + e.toString());
        } finally {
          IOUtils.closeQuietly(initFile);
        }
      }
    }
    return engine;
  }
Example #22
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;
  }
Example #23
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());
    }
  }
Example #24
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;
  }
Example #25
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;
  }
Example #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;
  }
 @Test
 public void putPrimitiveDoubleArray() throws ScriptException {
   double[] doubles = new double[] {1.0, 2.0, 3.0, 4.0, 5.0};
   engine.put("doubles", doubles);
   DoubleArrayVector dav = (DoubleArrayVector) engine.eval("as.double(doubles)");
   assertThat(dav.length(), equalTo(5));
 }
Example #28
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;
  }
Example #29
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;
  }
Example #30
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);
    }
  }