/** Test of get method, of class Jsr223JRubyEngine. */ @Test public void testGet() { logger1.info("get"); ScriptEngine instance; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "transient"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.put("abc", "aabc"); instance.put("@abc", "abbc"); instance.put("$abc", "abcc"); String key = "abc"; Object expResult = "aabc"; Object result = instance.get(key); assertEquals(expResult, result); List list = new ArrayList(); list.add("aabc"); instance.put("abc", list); Map map = new HashMap(); map.put("Ruby", "Rocks"); instance.put("@abc", map); result = instance.get(key); assertEquals(expResult, ((List) result).get(0)); key = "@abc"; expResult = "Rocks"; result = instance.get(key); assertEquals(expResult, ((Map) result).get("Ruby")); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
@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; }
// 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; }
@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); } }
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(); } }
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"); }
@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 boolean aggregableWithScript(UnderlayItem newItem, UnderlayItem topoStoreItem) { ScriptResult scriptResult = new ScriptResult(); scriptEngine.put("aggregable", scriptResult); scriptEngine.put("originalItem", topoStoreItem); scriptEngine.put("newItem", newItem); try { scriptEngine.eval(script); return scriptResult.getResult(); } catch (ScriptException e) { throw new IllegalStateException("Exception during script evaluation: " + script, e); } }
/** * {@inheritDoc} * * @see schemacrawler.tools.integration.TemplatedSchemaRenderer#render(java.lang.String, * schemacrawler.schema.Schema, java.io.Writer) */ @Override protected void render( final Connection connection, final String scriptFileName, final Database database, final Writer writer) throws ExecutionException { if (sf.util.Utility.isBlank(scriptFileName)) { throw new ExecutionException("No script file provided"); } final Reader reader; final File scriptFile = new File(scriptFileName); if (scriptFile.exists() && scriptFile.canRead()) { try { reader = new FileReader(scriptFile); } catch (final FileNotFoundException e) { throw new ExecutionException("Cannot load script, " + scriptFile.getAbsolutePath()); } } else { final InputStream inputStream = ScriptRenderer.class.getResourceAsStream("/" + scriptFileName); if (inputStream != null) { reader = new InputStreamReader(inputStream); } else { throw new ExecutionException("Cannot load script, " + scriptFileName); } } try { // Create a new instance of the engine final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension(FileUtility.getFileExtension(scriptFile)); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); } if (scriptEngine == null) { throw new ExecutionException("Script engine not found"); } // Set up the context scriptEngine.getContext().setWriter(writer); scriptEngine.put("database", database); scriptEngine.put("connection", connection); // Evaluate the script scriptEngine.eval(reader); } catch (final ScriptException e) { throw new ExecutionException("Could not evaluate script", e); } }
@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 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; }
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 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; }
@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 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 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; }
public Object execute(Object obj, String script) { MetaEntity info = infoFactory.getTypeInfo(obj.getClass().getName()); List<MetaAttribute> attrs = info.getAttributes(); Iterator<MetaAttribute> it = attrs.iterator(); while (it.hasNext()) { MetaAttribute attr = (MetaAttribute) it.next(); engine.put(attr.getName(), attr.getValue(obj)); } engine.put("rec", obj); try { return engine.eval(script); } catch (ScriptException ex) { new RuntimeException("Ejecutando Script", ex); return null; } }
LocalScriptEngine( String name, Instrumentation instrumentation, Unsafe unsafe, ToolingInterface tools) throws RemoteException { this.engine = new ScriptEngineManager().getEngineByName(name); if (engine == null) { throw new IllegalArgumentException(String.format("No such script engine '%s'.", name)); } if (instrumentation != null) { engine.put("instrumentation", instrumentation); } if (unsafe != null) { engine.put("unsafe", unsafe); } if (tools != null) { engine.put("tools", tools); } }
@BeforeClass public static void setUpClass() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); e = m.getEngineByName("nashorn"); o = new SharedObject(); e.put("o", o); e.eval("var SharedObject = Packages.jdk.nashorn.api.javaaccess.SharedObject;"); }
@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)); }
public static void main(String[] args) throws IOException, ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("Renjin"); engine.put("benchmarkArgs", new StringArrayVector(args)); engine.eval(new InputStreamReader(new FileInputStream("src/main/R/runner.R"))); }
public Object executeArgs(Object[] args, String script) { engine.put("arg", args); try { return engine.eval(script); } catch (ScriptException ex) { new RuntimeException("Ejecutando Script", ex); return null; } }
private Double customShapeArea() { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); coordinates.forEach((k, v) -> engine.put(k, v)); try { return (Double) engine.eval(shapeType.getFormula()); } catch (ScriptException ex) { return null; } }
private boolean eval(IElementValue context, String rule, ArrayList<Exception> lex) { rule = addPackages(rule); boolean returnValue = false; try { // if( // context.getSemanticElement().getName().equalsIgnoreCase("MedicationEnteringOrganizationIdentifier") ) { // test((XElementValue)context, m_value); // } engine.put("value", context); if (null != m_name && 0 < m_name.length()) { engine.put(m_name, m_value); } engine.put("returnValue", returnValue); engine.eval(rule); } catch (Exception ex) { lex.add(ex); } return returnValue; }
@Override public void acceptRepresentation(Representation entity) throws ResourceException { Form form = getRequest().getEntityAsForm(); chosenEngine = form.getFirstValue("engine"); script = form.getFirstValue("script"); if (StringUtils.isBlank(script)) { script = ""; } ScriptEngine eng = MANAGER.getEngineByName(chosenEngine); StringWriter rawString = new StringWriter(); PrintWriter rawOut = new PrintWriter(rawString); eng.put("rawOut", rawOut); StringWriter htmlString = new StringWriter(); PrintWriter htmlOut = new PrintWriter(htmlString); eng.put("htmlOut", htmlOut); eng.put("job", cj); eng.put("appCtx", cj.getJobContext()); eng.put("scriptResource", this); try { eng.eval(script); linesExecuted = script.split("\r?\n").length; } catch (ScriptException e) { ex = e; } catch (RuntimeException e) { ex = e; } finally { rawOut.flush(); rawOutput = rawString.toString(); htmlOut.flush(); htmlOutput = htmlString.toString(); eng.put("rawOut", null); eng.put("htmlOut", null); eng.put("job", null); eng.put("appCtx", null); eng.put("scriptResource", null); } // TODO: log script, results somewhere; job log INFO? getResponse().setEntity(represent()); }
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)); }
public ScriptPlugin(PluginLoader pluginLoader, Server instance, File plugin, ScriptEngine engine) throws InvalidDescriptionException { loader = pluginLoader; server = instance; file = plugin; rdescription = (Map<String, Object>) Utils.getOrExcept(engine, "SCRIPT_PDF"); description = Utils.getPdfFromMap(rdescription); logger = Logger.getLogger("Minecraft.JxplPlugin." + description.getName()); dataFolder = initialiseDataFolder(); helper = new PluginHelper(); engine.put(Utils.getOrDefault(rdescription, "jxpl.helpervarname", "helper"), helper); engine.put(Utils.getOrDefault(rdescription, "jxpl.pluginvarname", "plugin"), this); engine.put(Utils.getOrDefault(rdescription, "jxpl.servervarname", "server"), server); sEngine = (Invocable) engine; if (dataFolder != null && Utils.getOrDefault(rdescription, "jxpl.hasconfig", false)) { configFile = new File(dataFolder, "config.yml"); } else { configFile = null; } }
public void execute(Bindings bindings) { try { for (String key : bindings.keySet()) { engine.put(key, bindings.get(key)); } compiledScript.eval(); } catch (ScriptException e) { onScriptError(e); return; } }
protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); try { Configuration configuration = context.getConfiguration(); mapOutputKey = MrUtils.getWritableComparableType("js.map.output.key.type", configuration); mapOutputValue = MrUtils.getWritableComparableType("js.map.output.value.type", configuration); scriptEngine.eval( MrUtils.getScripts( context.getConfiguration(), MrUtils.getPathFilter("js.map.filename", configuration))); scriptEngine.put("mapOutputKey", mapOutputKey); scriptEngine.put("mapOutputValue", mapOutputValue); OUTPUT_KEY_CLASS = mapOutputKey.getClass(); OUTPUT_VALUE_CLASS = mapOutputValue.getClass(); } catch (ScriptException se) { IOException ioe = new IOException(se); ioe.setStackTrace(se.getStackTrace()); throw ioe; } }