@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));
 }
  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 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));
  }
 @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));
 }
 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 putPrimitiveIntegerArray() throws ScriptException {
   int[] integers = new int[] {1, 2, 3, 4, 5};
   engine.put("integers", integers);
   IntArrayVector iav = (IntArrayVector) engine.eval("as.integer(integers)");
   System.out.println(iav);
   assertThat(iav.length(), equalTo(5));
 }
  @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));
  }
  private L2ScriptEngineManager() {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
    if (Config.SCRIPT_CACHE) {
      _cache = loadCompiledScriptCache();
    } else {
      _cache = null;
    }
    _log.info("Initializing Script Engine Manager");

    for (ScriptEngineFactory factory : factories) {
      try {
        ScriptEngine engine = factory.getScriptEngine();
        boolean reg = false;
        for (String name : factory.getNames()) {
          ScriptEngine existentEngine = _nameEngines.get(name);

          if (existentEngine != null) {
            double engineVer = Double.parseDouble(factory.getEngineVersion());
            double existentEngVer =
                Double.parseDouble(existentEngine.getFactory().getEngineVersion());

            if (engineVer <= existentEngVer) {
              continue;
            }
          }

          reg = true;
          _nameEngines.put(name, engine);
        }

        if (reg) {
          _log.info(
              "Script Engine: "
                  + factory.getEngineName()
                  + " "
                  + factory.getEngineVersion()
                  + " - Language: "
                  + factory.getLanguageName()
                  + " - Language Version: "
                  + factory.getLanguageVersion());
        }

        for (String ext : factory.getExtensions()) {
          if (!ext.equals("java") || factory.getLanguageName().equals("java")) {
            _extEngines.put(ext, engine);
          }
        }
      } catch (Exception e) {
        _log.warn("Failed initializing factory. ");
        e.printStackTrace();
      }
    }

    preConfigure();
  }
  /* Utility functions for the binding classes */
  protected static ScriptEngine createScriptEngine(String language) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName(language);

    ScriptContext scriptContext = engine.getContext();
    Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
    scriptContext.setBindings(new JSFBindings(bindings), ScriptContext.ENGINE_SCOPE);

    return engine;
  }
Example #10
0
 private static void eval(ScriptEngine engine, String name) throws Exception {
   /*
    * This class is compiled into a jar file. The jar file
    * contains few scripts under /resources URL.
    */
   InputStream is = Main.class.getResourceAsStream("/resources/" + name);
   // current script file name for better error messages
   engine.put(ScriptEngine.FILENAME, name);
   // evaluate the script in the InputStream
   engine.eval(new InputStreamReader(is));
 }
  @Test
  public void putJavaObject() throws ScriptException {
    // create a script engine manager
    RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory();

    // create an R engine
    ScriptEngine engine = factory.getScriptEngine();

    HashMap<String, String> h = new HashMap<String, String>();
    engine.put("h", h);
    engine.eval("import(java.util.HashMap) \n" + " print(h$size())");
  }
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      System.out.println("No file specified");
      return;
    }

    InputStreamReader r = new InputStreamReader(new FileInputStream(args[0]));
    ScriptEngine engine = new EmbeddedRhinoScriptEngine();

    SimpleScriptContext context = new SimpleScriptContext();
    engine.put(ScriptEngine.FILENAME, args[0]);
    engine.eval(r, context);
    context.getWriter().flush();
  }
  /**
   * Method for receiving an input parameter and evaluating the value of the script. The method will
   * only evaluate the script if all input parameters have been received.
   *
   * @param in A parameter required to evaluate the script.
   * @return A parameter holding the return value of the script. May be null if the script could not
   *     evaluate.
   */
  public Named calculate(Named in) {

    LOG.debug(
        "Script '"
            + request.name
            + "': received dependent object '"
            + in.getName()
            + "' with timestamp '"
            + in.getTimestamp()
            + "'.");

    Named returnValue = null;

    try {
      /** Bind the parameter to the script. */
      if (request.inputBinding.get(in.getName()) == null) {
        LOG.error(
            "Script '"
                + request.name
                + "': Error in binding of parameters. The runtime parameter '"
                + in.getName()
                + "' was received, but has not been bound to any script parameter.");
      } else {
        engine.put(request.inputBinding.get(in.getName()), in);

        /** Check if a binding has been created for all needed parameters. */
        if (ready()) {
          LOG.info(
              "Script '"
                  + request.name
                  + "': All dependent values set. Evaluating script that will create object '"
                  + request.output.getName()
                  + "'");
          engine.eval(request.script);

          /**
           * The request output object has been bound to the engine. The script can thus update it
           * directly. Only the timestamp and uuid should also be set.
           */
          returnValue = request.output.instance();
          returnValue.setTimestamp(in.getTimestamp());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return returnValue;
  }
Example #14
0
  /**
   * Perform mediation with static inline script of the given scripting language
   *
   * @param synCtx message context
   * @return true, or the script return value
   * @throws ScriptException For any errors , when compile , run the script
   */
  private Object mediateForInlineScript(MessageContext synCtx) throws ScriptException {
    ScriptMessageContext scriptMC = new ScriptMessageContext(synCtx, xmlHelper);
    processJSONPayload(synCtx, scriptMC);
    Bindings bindings = scriptEngine.createBindings();
    bindings.put(MC_VAR_NAME, scriptMC);

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

    return response;
  }
  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();
        }
      }
    }
  }
 private String evaluateExpression(
     Execution execution, String scriptToExecute, JCRSessionWrapper session)
     throws RepositoryException, ScriptException {
   ScriptContext scriptContext = scriptEngine.getContext();
   if (bindings == null) {
     bindings = getBindings(execution, session);
   }
   scriptContext.setWriter(new StringWriter());
   scriptContext.setErrorWriter(new StringWriter());
   scriptEngine.eval(scriptToExecute, bindings);
   String error = scriptContext.getErrorWriter().toString();
   if (error.length() > 0) {
     logger.error("Scripting error : " + error);
   }
   return scriptContext.getWriter().toString().trim();
 }
Example #17
0
 public static void main(String[] args) throws Exception {
   ScriptEngineManager manager = new ScriptEngineManager();
   ScriptEngine jsengine = Helper.getJsEngine(manager);
   if (jsengine == null) {
     System.out.println("Warning: No js engine found; test vacuously passes.");
     return;
   }
   String langVersion = jsengine.getFactory().getLanguageVersion();
   if (!langVersion.equals(JS_LANG_VERSION)) {
     throw new RuntimeException("Expected JavaScript version is " + JS_LANG_VERSION);
   }
   String engineVersion = jsengine.getFactory().getEngineVersion();
   if (!engineVersion.equals(JS_ENGINE_VERSION)) {
     throw new RuntimeException("Expected Rhino version is " + JS_ENGINE_VERSION);
   }
 }
 public double[] fitfunc(double[] fitparams) {
   Bindings b = engine.createBindings();
   for (int i = 0; i < 10; i++) b.put("P" + (i + 1), fitparams[i]);
   /*String script1="P1="+fitparams[0]+"; "+
   "P2="+fitparams[1]+"; "+
   "P3="+fitparams[2]+"; "+
   "P4="+fitparams[3]+"; "+
   "P5="+fitparams[4]+"; "+
   "P6="+fitparams[5]+"; "+
   "P7="+fitparams[6]+"; "+
   "P8="+fitparams[7]+"; "+
   "P9="+fitparams[8]+"; "+
   "P10="+fitparams[9]+"; "+
   exdef+"; x=";
   String script2="; retval="+function+";";*/
   try {
     double[] temp = new double[tempx.length];
     for (int i = 0; i < tempx.length; i++) {
       // temp[i]=((Double)engine.eval(script1+(double)tempx[i]+script2)).doubleValue();
       b.put("x", tempx[i]);
       b.put("y", tempdata[i]);
       temp[i] = (Double) cs.eval(b);
     }
     return temp;
   } catch (Exception e) {
     IJ.log(e.getMessage());
     return null;
   }
 }
Example #19
0
 private void processJSONPayload(MessageContext synCtx, ScriptMessageContext scriptMC)
     throws ScriptException {
   if (!(synCtx instanceof Axis2MessageContext)) {
     return;
   }
   org.apache.axis2.context.MessageContext messageContext =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   String contentType = (String) messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE);
   if ("application/json".equals(contentType)) {
     String jsonString = (String) messageContext.getProperty("JSON_STRING");
     InputStream jsonStream = (InputStream) messageContext.getProperty("JSON_STREAM");
     String jsonPayload = "{}";
     prepareForJSON(scriptMC);
     if (jsonString != null) {
       jsonPayload = jsonParser.parse(jsonString).toString();
     } else if (jsonStream != null) {
       try {
         jsonString =
             IOUtils.toString(
                 jsonStream,
                 (String)
                     messageContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
         jsonPayload = jsonParser.parse(jsonString).toString();
       } catch (IOException e) {
         handleException("Failed to get the JSON payload string from the input stream.");
       }
       messageContext.setProperty("JSON_STRING", jsonPayload);
     }
     Object jsonObject = scriptEngine.eval('(' + jsonPayload + ')');
     synCtx.setProperty("JSON_OBJECT", jsonObject);
   }
 }
Example #20
0
 public String calculate(String exp) {
   String res = null;
   init(exp);
   calculate();
   res = (String) expVector.elementAt(0);
   return se.getVarList().getValue(res);
 }
Example #21
0
  public static void main(String[] args) throws Exception {

    // create a ScriptEngineManager
    ScriptEngineManager m = new ScriptEngineManager();
    // get an instance of JavaScript script engine
    ScriptEngine engine = m.getEngineByName("js");

    // expose the current script engine as a global variable
    engine.put("engine", engine);

    // evaluate few scripts that are bundled in "resources"
    eval(engine, "conc.js");
    eval(engine, "gui.js");
    eval(engine, "scriptpad.js");
    eval(engine, "mm.js");
  }
  @Test
  public void invokeMethod() throws ScriptException, NoSuchMethodException {
    Object obj = engine.eval("list(execute=sqrt)");
    DoubleVector result = (DoubleVector) invocableEngine.invokeMethod(obj, "execute", 16);

    assertThat(result.length(), equalTo(1));
    assertThat(result.get(0), equalTo(4d));
  }
  @Test
  public void getInterface() throws ScriptException {

    engine.eval("calculate <- function(x) sqrt(x)");
    Calculator calculator = invocableEngine.getInterface(Calculator.class);

    assertThat(calculator.calculate(64), equalTo(8d));
  }
  @Test
  public void invokeFunction() throws ScriptException, NoSuchMethodException {
    engine.eval("f <- function(x) sqrt(x)");
    DoubleVector result = (DoubleVector) invocableEngine.invokeFunction("f", 4);

    assertThat(result.length(), equalTo(1));
    assertThat(result.get(0), equalTo(2d));
  }
Example #25
0
 public static void main(String[] args) throws Exception {
   System.out.println("\nTest7\n");
   File file = new File(System.getProperty("test.src", "."), "Test7.js");
   Reader r = new FileReader(file);
   ScriptEngineManager m = new ScriptEngineManager();
   ScriptEngine eng = Helper.getJsEngine(m);
   if (eng == null) {
     System.out.println("Warning: No js engine found; test vacuously passes.");
     return;
   }
   eng.put("filename", file.getAbsolutePath());
   eng.eval(r);
   String str = (String) eng.get("firstLine");
   // do not change first line in Test7.js -- we check it here!
   if (!str.equals("//this is the first line of Test7.js")) {
     throw new RuntimeException("unexpected first line");
   }
 }
Example #26
0
 /** Will load the script source from the provided filename. */
 public static void loadScript(String script_name) {
   try {
     js_engine.eval(new java.io.FileReader(script_name));
   } catch (ScriptException se) {
     se.printStackTrace();
   } catch (java.io.IOException iox) {
     iox.printStackTrace();
   }
 }
  /**
   * 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;
  }
    @Override
    public Object getValue(FacesContext context)
        throws EvaluationException, PropertyNotFoundException {
      Object result = null;
      try {
        ScriptEngine engine = (ScriptEngine) getScopeMap().get("_" + language + "ScriptEngine");
        if (engine == null) {
          engine = GenericBindingFactory.createScriptEngine(language);
          getScopeMap().put("_" + language + "ScriptEngine", engine);
        }

        includeScriptLibraries(engine);

        result = engine.eval(this.content);
      } catch (ScriptException se) {
        throw new EvaluationException(se);
      }
      return result;
    }
  private void initScript() {
    String scriptName = "src" + File.separator + "jscripts" + File.separator + "CreateWorld.js";
    List<ScriptEngineFactory> list = factory.getEngineFactories();
    File scriptFile = new File(scriptName);

    try {
      FileReader fileReader = new FileReader(scriptFile);
      engine.eval(fileReader);
      fileReader.close();
    } catch (FileNotFoundException e1) {
      System.out.println(scriptName + " not found " + e1);
    } catch (IOException e2) {
      System.out.println("IO issue detected " + scriptName + e2);
    } catch (ScriptException e3) {
      System.out.println("ScriptException in " + scriptName + e3);
    } catch (NullPointerException e4) {
      System.out.println("Null pointer in" + scriptName + e4);
    }
    addGameWorldObject((SceneNode) engine.get("worldAxis"));
  }
  @SuppressWarnings("unchecked")
  protected static void includeScriptLibraries(ScriptEngine engine) throws ScriptException {
    FacesContext context = FacesContext.getCurrentInstance();

    String language = engine.getFactory().getLanguageName();
    Set<String> mimeTypes = new HashSet<String>(engine.getFactory().getMimeTypes());
    mimeTypes.add("text/x-script-" + language);

    Set<String> includedLibraries =
        (Set<String>) getScopeMap().get("_" + language + "IncludedLibraries");
    if (includedLibraries == null) {
      includedLibraries = new HashSet<String>();
      getScopeMap().put("_" + language + "IncludedLibraries", includedLibraries);
    }

    // Now look through the view's resources for appropriate scripts and load them
    UIViewRootEx2 view = (UIViewRootEx2) context.getViewRoot();
    if (view != null) {
      for (Resource res : view.getResources()) {
        if (res instanceof ScriptResource) {
          ScriptResource script = (ScriptResource) res;
          if (script.getType() != null && mimeTypes.contains(script.getType())) {
            // Then we have a script - find its contents and run it

            String properName = (script.getSrc().charAt(0) == '/' ? "" : "/") + script.getSrc();
            if (!includedLibraries.contains(properName)) {
              InputStream is =
                  context
                      .getExternalContext()
                      .getResourceAsStream("/WEB-INF/" + language + properName);
              if (is != null) {
                engine.eval(new InputStreamReader(is));
              }

              includedLibraries.add(properName);
            }
          }
        }
      }
    }
  }