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 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)); }
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 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 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)); }
@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)); }
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); } }
@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 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)); }
@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)); }
/** 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(); } }
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())"); }
boolean init_functions() { GenericDialog gd = new GenericDialog("Fitting Options"); gd.addStringField("Extra Definitions", exdef, 50); gd.addCheckbox("Weight Using Plot Errors", false); gd.addStringField("Weighting Equation (y is for data)", weightfunction, 50); gd.addStringField("Fit_Equation", function, 50); gd.showDialog(); if (gd.wasCanceled()) { return false; } exdef = gd.getNextString(); boolean errweights = gd.getNextBoolean(); weightfunction = gd.getNextString(); function = gd.getNextString(); // first initialize the weights weights = new float[tempdata.length]; if (errweights || weightfunction.equals("") || weightfunction == null || weightfunction == "1.0") { if (errweights) { for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f / (errs[i] * errs[i]); } else { for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f; } } else { for (int i = 0; i < tempdata.length; i++) { String script = "y =" + tempdata[i] + "; " + "x =" + tempx[i] + "; " + "retval=" + weightfunction + ";"; Double temp = new Double(0.0); try { temp = (Double) engine.eval(script); } catch (Exception e) { IJ.log(e.getMessage()); } if (!(temp.isInfinite() || temp.isNaN())) { weights[i] = temp.floatValue(); } } } // now compile the function script try { String script1 = exdef + "; retval=" + function + ";"; cs = ce.compile(script1); } catch (Exception e) { IJ.log(e.toString()); return false; } return true; }
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; }
/** * 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; }
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(); }
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"); } }
@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); } } } } } }
@Override public Object invoke(FacesContext context, Object[] arg1) throws EvaluationException, MethodNotFoundException { 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); } if (!(result instanceof Serializable)) { return result.toString(); } return result; }
@EventHandler public void onPacketProcess(PacketProcessEvent event) { // System.out.println("Packet received: " + event.getPacket().getId() // + " (" + event.getPacket() + ")"); Packet packet = event.getPacket(); switch (packet.getId()) { case 0: connectionHandler.sendPacket(new Packet0KeepAlive(new Random().nextInt())); break; case 3: String message = ((Packet3Chat) packet).message; message = removeColors(message); System.out.println("[" + bot.getSession().getUsername() + "] " + message); String testMessage = "[MineCaptcha] To be unmuted answer this question: What is "; String testMessage2 = "Please type '"; String testMessage3 = "' to continue sending messages/commands"; if (message.contains(testMessage)) { try { String captcha = message.split(Pattern.quote(testMessage))[1].split("[ \\?]")[0]; ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String solved = engine.eval(captcha).toString(); solved = solved.split("\\.")[0]; connectionHandler.sendPacket(new Packet3Chat(solved)); } catch (Exception exception) { exception.printStackTrace(); } } else if (message.contains(testMessage2) && message.contains(testMessage3)) { try { String captcha = message.split(Pattern.quote(testMessage2))[1].split(Pattern.quote(testMessage3))[0]; connectionHandler.sendPacket(new Packet3Chat(captcha)); } catch (Exception exception) { exception.printStackTrace(); } } else if (message.startsWith("Please register with \"/register")) { String password = ""; for (int i = 0; i < 10 + random.nextInt(6); i++) password += alphas[random.nextInt(alphas.length)]; bot.say("/register " + password + " " + password); } else if (message.startsWith("/uc ")) { connectionHandler.sendPacket(new Packet3Chat(message)); } else if ((message.contains("do the crime") && message.contains("do the time")) || message.contains("You have been muted")) { connectionHandler.sendPacket(new Packet3Chat("\247Leaving!")); } else if (message.contains(owner + " has requested to teleport to you.")) { connectionHandler.sendPacket(new Packet3Chat("/tpaccept")); } else if (message.contains(owner)) { if (message.contains("Go ")) { spamMessage = message.substring(message.indexOf("Go ") + "Go ".length()); } else if (message.contains("Stop")) { spamMessage = null; bot.getTaskManager().stopAll(); } else if (message.contains("Die")) { die = true; } else if (message.contains("Say ")) { connectionHandler.sendPacket( new Packet3Chat(message.substring(message.indexOf("Say ") + "Say ".length()))); } else if (message.contains("Leave")) { connectionHandler.sendPacket(new Packet255KickDisconnect("Quit")); } else if (message.contains("Tool")) { MainPlayerEntity player = bot.getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); inventory.setCurrentHeldSlot( Integer.parseInt( message.substring(message.indexOf("Tool ") + "Tool ".length()).split(" ")[0])); } else if (message.contains("DropId ")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); String substring = message.substring(message.indexOf("DropId ") + "DropId ".length()).split(" ")[0]; int id = Integer.parseInt(substring); for (int slot = 0; slot < 40; slot++) { ItemStack item = inventory.getItemAt(slot); if (item != null && item.getId() == id) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } } inventory.close(); } else if (message.contains("Drop")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); if (message.contains("Drop ")) { String substring = message.substring(message.indexOf("Drop ") + "Drop ".length()).split(" ")[0]; try { int slot = Integer.parseInt(substring); if (slot < 0 || slot >= 40) return; if (inventory.getItemAt(slot) != null) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } return; } catch (NumberFormatException e) { } } for (int slot = 0; slot < 40; slot++) { if (inventory.getItemAt(slot) != null) { inventory.selectItemAt(slot, true); inventory.dropSelectedItem(); } } inventory.close(); } else if (message.contains("Switch ")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); String substring = message.substring(message.indexOf("Switch ") + "Switch ".length()); try { int slot1 = Integer.parseInt(substring.split(" ")[0]); int slot2 = Integer.parseInt(substring.split(" ")[1]); if (slot1 < 0 || slot1 >= 45 || slot2 < 0 || slot2 >= 45) return; inventory.selectItemAt(slot1); inventory.selectItemAt(slot2); inventory.selectItemAt(slot1); } catch (NumberFormatException e) { } // inventory.close(); } else if (message.contains("Equip")) { MainPlayerEntity player = bot.getPlayer(); PlayerInventory inventory = player.getInventory(); boolean helmet = inventory.getArmorAt(0) != null; boolean chestplate = inventory.getArmorAt(1) != null; boolean leggings = inventory.getArmorAt(2) != null; boolean boots = inventory.getArmorAt(3) != null; boolean changed = false; for (int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if (item == null) continue; int armorSlot; int id = item.getId(); if (!helmet && (id == 86 || id == 298 || id == 302 || id == 306 || id == 310 || id == 314)) { armorSlot = 0; helmet = true; } else if (!chestplate && (id == 299 || id == 303 || id == 307 || id == 311 || id == 315)) { armorSlot = 1; chestplate = true; } else if (!leggings && (id == 300 || id == 304 || id == 308 || id == 312 || id == 316)) { armorSlot = 2; leggings = true; } else if (!boots && (id == 301 || id == 305 || id == 309 || id == 313 || id == 317)) { armorSlot = 3; boots = true; } else if (helmet && chestplate && leggings && boots) break; else continue; inventory.selectItemAt(i); inventory.selectArmorAt(armorSlot); changed = true; } if (!changed) { for (int i = 0; i < 36; i++) { ItemStack item = inventory.getItemAt(i); if (item != null) continue; int armorSlot; if (helmet) { armorSlot = 0; helmet = false; } else if (chestplate) { armorSlot = 1; chestplate = false; } else if (leggings) { armorSlot = 2; leggings = false; } else if (boots) { armorSlot = 3; boots = false; } else if (!helmet && !chestplate && !leggings && !boots) break; else continue; inventory.selectArmorAt(armorSlot); inventory.selectItemAt(i); } } inventory.close(); bot.say("Equipped armor."); } else if (message.contains("Owner ")) { String name = message.substring(message.indexOf("Owner ") + "Owner ".length()).split(" ")[0]; owner = name; bot.say("Set owner to " + name); } } else if (message.contains("You are not member of any faction.") && spamMessage != null && createFaction) { String msg = "/f create "; for (int i = 0; i < 7 + random.nextInt(3); i++) msg += alphas[random.nextInt(alphas.length)]; bot.say(msg); } if (message.matches("[\\*]*SPQR [\\w]{1,16} invited you to SPQR")) { bot.say("/f join SPQR"); bot.say("\247asdf"); } break; case 8: Packet8UpdateHealth updateHealth = (Packet8UpdateHealth) packet; if (updateHealth.healthMP <= 0) connectionHandler.sendPacket(new Packet205ClientCommand(1)); break; case 9: TaskManager taskManager = bot.getTaskManager(); taskManager.stopAll(); break; } }
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (Config.SCRIPT_DEBUG) { _log.info("Loading Script: " + file.getAbsolutePath()); } if (Config.SCRIPT_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && Config.SCRIPT_ALLOW_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute( "mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (Config.SCRIPT_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute( "mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute( "sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); } } }
/** * Prepares the mediator for the invocation of an external script * * @param synCtx MessageContext script * @throws ScriptException For any errors , when compile the script */ protected synchronized void prepareExternalScript(MessageContext synCtx) throws ScriptException { // TODO: only need this synchronized method for dynamic registry entries. If there was a way // to access the registry entry during mediator initialization then for non-dynamic entries // this could be done just the once during mediator initialization. // Derive actual key from xpath expression or get static key String generatedScriptKey = key.evaluateValue(synCtx); Entry entry = synCtx.getConfiguration().getEntryDefinition(generatedScriptKey); boolean needsReload = (entry != null) && entry.isDynamic() && (!entry.isCached() || entry.isExpired()); synchronized (resourceLock) { if (scriptSourceCode == null || needsReload) { Object o = synCtx.getEntry(generatedScriptKey); if (o instanceof OMElement) { scriptSourceCode = ((OMElement) (o)).getText(); scriptEngine.eval(scriptSourceCode); } else if (o instanceof String) { scriptSourceCode = (String) o; scriptEngine.eval(scriptSourceCode); } else if (o instanceof OMText) { DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler(); if (dataHandler != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream())); scriptEngine.eval(reader); } catch (IOException e) { handleException("Error in reading script as a stream ", e, synCtx); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { handleException("Error in closing input stream ", e, synCtx); } } } } } } } // load <include /> scripts; reload each script if needed for (Value includeKey : includes.keySet()) { String includeSourceCode = (String) includes.get(includeKey); String generatedKey = includeKey.evaluateValue(synCtx); Entry includeEntry = synCtx.getConfiguration().getEntryDefinition(generatedKey); boolean includeEntryNeedsReload = (includeEntry != null) && includeEntry.isDynamic() && (!includeEntry.isCached() || includeEntry.isExpired()); synchronized (resourceLock) { if (includeSourceCode == null || includeEntryNeedsReload) { log.debug("Re-/Loading the include script with key " + includeKey); Object o = synCtx.getEntry(generatedKey); if (o instanceof OMElement) { includeSourceCode = ((OMElement) (o)).getText(); scriptEngine.eval(includeSourceCode); } else if (o instanceof String) { includeSourceCode = (String) o; scriptEngine.eval(includeSourceCode); } else if (o instanceof OMText) { DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler(); if (dataHandler != null) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream())); scriptEngine.eval(reader); } catch (IOException e) { handleException("Error in reading script as a stream ", e, synCtx); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { handleException("Error in closing input" + " stream ", e, synCtx); } } } } } } } } }
@Test public void statsPackageIsLoadedByDefault() throws ScriptException { engine.eval("dnorm(0)"); }
@Test public void helloWorld() throws ScriptException { // evaluate R code from String engine.eval("print('Hello, World')"); }
@Test public void readResource() throws ScriptException { StringVector vector = (StringVector) engine.eval("readLines('res:org/renjin/test.txt')"); assertThat(vector.length(), equalTo(1)); assertThat(vector.getElementAsString(0), equalTo("hello world")); }