static void nashornCompiledScript(String code) throws ScriptException, NoSuchMethodException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("nashorn"); CompiledScript compiled = ((Compilable) engine).compile(code); Object result = null; ScriptContext context = new SimpleScriptContext(); Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE); long total = 0; for (int i = 0; i < RUNS; ++i) { long start = System.nanoTime(); for (int j = 0; j < BATCH; ++j) { engineScope.put("value", "12345678"); result = compiled.eval(context); } 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 of getBindings method, of class Jsr223JRubyEngine. */ @Test public void testGetBindings() throws ScriptException { logger1.info("getBindings"); ScriptEngine instance; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "persistent"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.eval("p = 9.0"); instance.eval("q = Math.sqrt p"); Double expResult = 9.0; int scope = ScriptContext.ENGINE_SCOPE; Bindings result = instance.getBindings(scope); assertEquals(expResult, (Double) result.get("p"), 0.01); expResult = 3.0; assertEquals(expResult, (Double) result.get("q"), 0.01); scope = ScriptContext.GLOBAL_SCOPE; result = instance.getBindings(scope); // Bug of livetribe javax.script package impl. // assertTrue(result instanceof SimpleBindings); // assertEquals(0, result.size()); JRubyScriptEngineManager manager2 = new JRubyScriptEngineManager(); instance = (JRubyEngine) manager2.getEngineByName("jruby"); result = instance.getBindings(scope); assertTrue(result instanceof SimpleBindings); assertEquals(0, result.size()); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
/** Test 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; }
@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 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; }
/** 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; }
private Collection<Throwable> execute_fastq(String source) throws IOException { InputStream in = null; FourLinesFastqReader iter = null; try { if (source == null) { in = stdin(); } else { in = IOUtils.openURIForReading(source); } iter = new FourLinesFastqReader(in); bindings.put("iter", in); bindings.put("format", "fastq"); this.script.eval(bindings); return RETURN_OK; } catch (Exception e) { LOG.error(e); return wrapException(e); } finally { CloserUtil.close(iter); CloserUtil.close(in); bindings.remove("header"); bindings.remove("iter"); bindings.remove("format"); } }
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; }
public void testMethodIndirection() throws Exception { PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer(); ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null); Bindings bindings = engine.createBindings(); Tester tester = new Tester(); bindings.put("tester", tester); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); engine.eval("tester.increment()"); Assert.assertEquals(tester.getInvocationCoung(), 1, "Unexpected number of tester invocations."); Map<String, Set<Method>> methods = getMethodsByName(Tester.class); for (Set<Method> ms : methods.values()) { Set<String> fns = initializer.generateIndirectionMethods("tester", ms); for (String fn : fns) { engine.eval(fn); } } engine.eval("increment()"); Assert.assertEquals( tester.getInvocationCoung(), 2, "Unexpected number of tester invocations after calling an indirected method."); }
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; } }
/** * Execute the script and return the ScriptResult corresponding. This method can add an additional * user bindings if needed. * * @param aBindings the additional user bindings to add if needed. Can be null or empty. * @param outputSink where the script output is printed to. * @param errorSink where the script error stream is printed to. * @return a ScriptResult object. */ public ScriptResult<E> execute( Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) { ScriptEngine engine = createScriptEngine(); if (engine == null) return new ScriptResult<>( new Exception("No Script Engine Found for name or extension " + scriptEngineLookup)); // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE) BoundedStringWriter outputBoundedWriter = new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE); BoundedStringWriter errorBoundedWriter = new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE); engine.getContext().setWriter(new PrintWriter(outputBoundedWriter)); engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter)); Reader closedInput = new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new IOException("closed"); } @Override public void close() throws IOException {} }; engine.getContext().setReader(closedInput); engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE); try { Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); // add additional bindings if (aBindings != null) { for (Entry<String, Object> e : aBindings.entrySet()) { bindings.put(e.getKey(), e.getValue()); } } prepareBindings(bindings); Object evalResult = engine.eval(getReader()); engine.getContext().getErrorWriter().flush(); engine.getContext().getWriter().flush(); // Add output to the script result ScriptResult<E> result = this.getResult(evalResult, bindings); result.setOutput(outputBoundedWriter.toString()); return result; } catch (javax.script.ScriptException e) { // drop exception cause as it might not be serializable ScriptException scriptException = new ScriptException(e.getMessage()); scriptException.setStackTrace(e.getStackTrace()); return new ScriptResult<>(scriptException); } catch (Throwable t) { String stack = Throwables.getStackTraceAsString(t); if (t.getMessage() != null) { stack = t.getMessage() + System.lineSeparator() + stack; } return new ScriptResult<>(new Exception(stack)); } }
private Map<String, Object> mergeBindings( final Context context, final Bindings request, final Bindings... scopes) { Set<String> safeAttributes = null != request ? request.keySet() : Collections.EMPTY_SET; Map<String, Object> scope = new HashMap<String, Object>(); for (Map<String, Object> next : scopes) { if (null == next) { continue; } for (Map.Entry<String, Object> entry : next.entrySet()) { if (scope.containsKey(entry.getKey()) || safeAttributes.contains(entry.getKey())) { continue; } scope.put(entry.getKey(), entry.getValue()); } } // Make lazy deep copy if (!scope.isEmpty()) { scope = new LazyMap<String, Object>( new InnerMapFactory( scope, new OperationParameter(context, "DEFAULT", engine.getPersistenceConfig()))); } if (null == request || request.isEmpty()) { return scope; } else if (scope.isEmpty()) { return request; } else { request.putAll(scope); return request; } }
@Override public void handleRead(final Context context, final ReadRequest request, final Bindings handler) throws ResourceException { super.handleRead(context, request, handler); handler.put("request", request); handler.put("resources", configuration.get("resources").copy().getObject()); }
@Test public void shouldEvalScriptWithGlobalBindings() throws Exception { final Bindings b = new SimpleBindings(); b.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create(); assertEquals(2, gremlinExecutor.eval("1+x").get()); gremlinExecutor.close(); }
public Object eval(Reader script, ScriptContext scriptContext) throws ScriptException { Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING); if (helper == null) { throw new ScriptException("SlingScriptHelper missing from bindings"); } // ensure GET request if (helper.getRequest() != null && !"GET".equals(helper.getRequest().getMethod())) { throw new ScriptException("JRuby scripting only supports GET requests"); } final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); StringBuffer scriptString = new StringBuffer(); BufferedReader bufferedScript = new BufferedReader(script); String nextLine = bufferedScript.readLine(); while (nextLine != null) { scriptString.append(nextLine); scriptString.append("\n"); nextLine = bufferedScript.readLine(); } IRubyObject scriptRubyString = JavaEmbedUtils.javaToRuby(runtime, scriptString.toString()); IRubyObject erb = (IRubyObject) JavaEmbedUtils.invokeMethod( runtime, erbModule, "new", new Object[] {scriptRubyString}, IRubyObject.class); JavaEmbedUtils.invokeMethod( runtime, erb, "set_props", new Object[] {JavaEmbedUtils.javaToRuby(runtime, bindings)}, IRubyObject.class); IRubyObject binding = (IRubyObject) JavaEmbedUtils.invokeMethod( runtime, erb, "send", new Object[] {bindingSym}, IRubyObject.class); scriptContext .getWriter() .write( (String) JavaEmbedUtils.invokeMethod( runtime, erb, "result", new Object[] {binding}, String.class)); } catch (Throwable t) { final ScriptException ex = new ScriptException("Failure running Ruby script:" + t); ex.initCause(t); throw ex; } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } return null; }
/** Transfers variables from one interpreter's bindings to another. */ private void copyBindings(final ScriptInterpreter src, final ScriptInterpreter dest) { if (src == null) return; // nothing to copy final Bindings srcBindings = src.getBindings(); final Bindings destBindings = dest.getBindings(); for (final String key : src.getBindings().keySet()) { final Object value = src.getLanguage().decode(srcBindings.get(key)); destBindings.put(key, value); } }
@Test public void shouldGetGlobalBindings() throws Exception { final Bindings b = new SimpleBindings(); final Object bound = new Object(); b.put("x", bound); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(b).create(); assertEquals(bound, gremlinExecutor.getGlobalBindings().get("x")); gremlinExecutor.close(); }
@Test public void shouldEvalScriptWithLocalOverridingGlobalBindings() throws Exception { final Bindings g = new SimpleBindings(); g.put("x", 1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create(); final Bindings b = new SimpleBindings(); b.put("x", 10); assertEquals(11, gremlinExecutor.eval("x+1", b).get()); gremlinExecutor.close(); }
/** Populates the bindings with the context + services + gateways. */ private void populateBindings(final Bindings bindings) { bindings.put("ctx", context); for (final Service service : context.getServiceIndex().getAll()) { final String name = serviceName(service); bindings.put(name, service); } for (final Gateway gateway : gateways()) { bindings.put(gateway.getShortName(), gateway); } }
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; } }
public Map<String, Object> createModel(ScriptContext scriptContext) { Map<String, Object> model = new HashMap<>(); Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); for (Object entryObj : bindings.entrySet()) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) entryObj; model.put((String) entry.getKey(), entry.getValue()); } model.put("properties", new ScriptContextAdapter(scriptContext).getResource().getValueMap()); return model; }
public void actionPerformed(ActionEvent evt) { // clear selection list.getListComponent().clearSelection(); int from = fromSpinnerModel.getNumber().intValue(); int to = toSpinnerModel.getNumber().intValue(); try { ExpressionFormat format = new ExpressionFormat(textField.getText()); // pad episode numbers with zeros (e.g. %02d) so all numbers have the same number of // digits NumberFormat numberFormat = NumberFormat.getIntegerInstance(); numberFormat.setMinimumIntegerDigits(max(2, Integer.toString(max(from, to)).length())); numberFormat.setGroupingUsed(false); List<String> names = new ArrayList<String>(); int min = min(from, to); int max = max(from, to); for (int i = min; i <= max; i++) { Bindings bindings = new SimpleBindings(); // strings bindings.put("i", numberFormat.format(i)); // numbers bindings.put("index", i); bindings.put("from", from); bindings.put("to", to); names.add(format.format(bindings, new StringBuffer()).toString()); } if (signum(to - from) < 0) { Collections.reverse(names); } // try to match title from the first five names Collection<String> title = new SeriesNameMatcher() .matchAll( (names.size() < 5 ? names : names.subList(0, 4)).toArray(new String[0])); list.setTitle(title.isEmpty() ? "List" : title.iterator().next()); list.getModel().clear(); list.getModel().addAll(names); } catch (Exception e) { UILogger.log(Level.WARNING, ExceptionUtilities.getMessage(e), e); } }
@Test public void testRebinding() throws ScriptException { Bindings bindings = frege.getBindings(ENGINE_SCOPE); bindings.put("bar :: Integer", new BigInteger("12312332142343244")); final Object actual1 = frege.eval("bar + 3.big"); final Object expected1 = new BigInteger("12312332142343247"); bindings.put("bar :: String", "hello "); final Object actual2 = frege.eval("bar ++ \"world\""); final Object expected2 = "hello world"; assertEquals(expected1, actual1); assertEquals(expected2, actual2); }
private Bindings createBindings(Entity entity, Version version) { Bindings bindings = engine.createBindings(); Set<Metric> metrics = entity.getMetrics(); for (Metric metric : metrics) { Double metricValue = entity.getMetricValue(version, metric); bindings.put(metric.getNickname(), metricValue); } return bindings; }
private static void typeCastContextBindings(final ScriptContext context) { for (int scope : context.getScopes()) { Bindings bindings = context.getBindings(scope); if (!(bindings instanceof VariableLibrary) && null != bindings) { for (String key : bindings.keySet()) { Object object = bindings.get(key); if (object instanceof Atom) { bindings.put(key, ((Atom) object).getValue()); } } } } }
/** Lists variables in the script context. */ public void vars() { if (interpreter == null) return; // no active script language final List<String> keys = new ArrayList<>(); final List<Object> types = new ArrayList<>(); final Bindings bindings = interpreter.getBindings(); for (final String key : bindings.keySet()) { final Object value = bindings.get(key); keys.add(key); types.add(type(value)); } printColumns(keys, types); }
private ExtensionResponse tryExecuteGremlinScript( RexsterResourceContext rexsterResourceContext, Graph graph, Vertex vertex, Edge edge, String script) { ExtensionResponse extensionResponse; JSONObject requestObject = rexsterResourceContext.getRequestObject(); boolean showTypes = RequestObjectHelper.getShowTypes(requestObject); long offsetStart = RequestObjectHelper.getStartOffset(requestObject); long offsetEnd = RequestObjectHelper.getEndOffset(requestObject); Bindings bindings = new SimpleBindings(); bindings.put(GRAPH_VARIABLE, graph); bindings.put(VERTEX_VARIABLE, vertex); bindings.put(EDGE_VARIABLE, edge); // read the return keys from the request object List<String> returnKeys = RequestObjectHelper.getReturnKeys(requestObject, WILDCARD); ExtensionMethod extensionMethod = rexsterResourceContext.getExtensionMethod(); try { if (script != null && !script.isEmpty()) { Object result = engine.eval(script, bindings); JSONArray results = new JSONResultConverter(showTypes, offsetStart, offsetEnd, returnKeys).convert(result); HashMap<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put(Tokens.SUCCESS, true); resultMap.put(Tokens.RESULTS, results); JSONObject resultObject = new JSONObject(resultMap); extensionResponse = ExtensionResponse.ok(resultObject); } else { extensionResponse = ExtensionResponse.error( "no script provided", generateErrorJson(extensionMethod.getExtensionApiAsJson())); } } catch (Exception e) { extensionResponse = ExtensionResponse.error(e, generateErrorJson(extensionMethod.getExtensionApiAsJson())); } return extensionResponse; }
@Test public void testScript() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); manager.put("welcome", "hello"); // 设置全局变量 ScriptEngine engine = manager.getEngineByName("httl"); engine.put("page", "test"); // 设置引擎变量 Bindings bindings = engine.createBindings(); bindings.put("user", "liangfei"); // 设置执行变量 String result = (String) engine.eval( "#set(String welcome, String page, String user)${welcome}, ${user}, this is ${page} page."); // 执行表达式 assertEquals("hello, liangfei, this is test page.", result); }
private static Bindings createBindings( final Graph graph, final Vertex vertex, final Edge edge, final ScriptEngine scriptEngine) { final Bindings bindings = scriptEngine.createBindings(); bindings.put(GRAPH_VARIABLE, graph); if (vertex != null) { bindings.put(VERTEX_VARIABLE, vertex); } if (edge != null) { bindings.put(EDGE_VARIABLE, edge); } return bindings; }
private Bindings getBindings(Execution execution, JCRSessionWrapper session) throws RepositoryException { EnvironmentImpl environment = EnvironmentImpl.getCurrent(); final Map<String, Object> vars = ((ExecutionImpl) execution).getVariables(); Locale locale = (Locale) vars.get("locale"); final Bindings bindings = new MyBindings(environment); ResourceBundle resourceBundle = JahiaResourceBundle.lookupBundle( "org.jahia.services.workflow." + ((ExecutionImpl) execution).getProcessDefinition().getKey(), locale); bindings.put("bundle", resourceBundle); JahiaUser jahiaUser = ServicesRegistry.getInstance() .getJahiaUserManagerService() .lookupUserByKey((String) vars.get("user")); bindings.put("user", jahiaUser); bindings.put("date", new DateTool()); bindings.put("submissionDate", Calendar.getInstance()); bindings.put("locale", locale); bindings.put("workspace", vars.get("workspace")); List<JCRNodeWrapper> nodes = new LinkedList<JCRNodeWrapper>(); @SuppressWarnings("unchecked") List<String> stringList = (List<String>) vars.get("nodeIds"); for (String s : stringList) { JCRNodeWrapper nodeByUUID = session.getNodeByUUID(s); if (!nodeByUUID.isNodeType("jnt:translation")) { nodes.add(nodeByUUID); } } bindings.put("nodes", nodes); return bindings; }