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()); }
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; }
private Collection<Throwable> execute_bam(String source) throws IOException { SamReader in = null; SAMRecordIterator iter = null; try { SamReaderFactory srf = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT); if (source == null) { in = srf.open(SamInputResource.of(stdin())); } else { in = srf.open(SamInputResource.of(source)); } iter = in.iterator(); bindings.put("header", in.getFileHeader()); bindings.put("iter", iter); bindings.put("format", "sam"); this.script.eval(bindings); return RETURN_OK; } catch (Exception e) { LOG.error(e); return wrapException(e); } finally { CloserUtil.close(in); CloserUtil.close(iter); bindings.remove("header"); bindings.remove("iter"); bindings.remove("format"); } }
/** 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 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; }
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; } }
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"); } }
@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 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 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 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; }
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; }
@SuppressWarnings("unchecked") public CustomType customClassValue(Object jsNode) { try { List<UserClassData> classesList = new ArrayList<UserClassData>(); Bindings bindings = this.getBindings(); bindings.put("node", jsNode); bindings.put("env", this.wrapper); bindings.put("pkg", ModelRegistry.getInstance().rootPackage()); ScriptObjectMirror svData = (ScriptObjectMirror) engine.eval("env.generateClasses(node.value(),pkg)", bindings); String jsonData = null; String valueName = null; if (svData != null) { jsonData = svData.get("data").toString(); valueName = svData.get("valueName").toString(); ScriptObjectMirror classes = (ScriptObjectMirror) svData.get("classes"); for (Object obj : classes.values()) { ScriptObjectMirror cls = (ScriptObjectMirror) obj; String classContent = cls.get("content").toString(); String qName = cls.get("qualifiedName").toString(); String sName = cls.get("simpleName").toString(); classesList.add(new UserClassData(qName, sName, classContent)); } } String sName = classesList.get(0).getSimpleName(); String qName = classesList.get(0).getQualifiedName(); Class<? extends CustomType> customClass = loadCustomClassFromLibrary(sName); if (customClass == null) { setClassLoaderParams(classesList); Class<?> c = customClassLoader.loadClass(qName); if (c != null && CustomType.class.isAssignableFrom(c)) { customClass = (Class<? extends CustomType>) c; } } if (customClass != null) { CustomType result = unmarshalCustomType(jsonData, (Class<? extends CustomType>) customClass); result.setRAMLValueName(valueName); return result; } } catch (Exception e) { e.printStackTrace(); } CustomType customType = new CustomType(); customType.setFactory(this); return customType; }
/** 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; }
public void addFunctionBinding(ReturnableScriptMethodSPI method) { scriptBindings.put("this" + method.getFunctionName(), method); String scriptx = "function " + method.getFunctionName() + "() {\n" + "\tvar args = java.lang.reflect.Array.newInstance(java.lang.Object, arguments.length);\n" + "\tfor(var i = 0; i < arguments.length; i++) {\n" + "\t\targs[i] = arguments[i];\n" + "\t}\n" + "\tthis" + method.getFunctionName() + ".setArguments(args);\n" + "\tthis" + method.getFunctionName() + ".run();\n" + "\tvar tmp = this" + method.getFunctionName() + ".returns();\n" + "\treturn tmp\n;" + "}"; try { // System.out.println("evaluating script: \n"+scriptx); scriptEngine.eval(scriptx, scriptBindings); } catch (ScriptException e) { e.printStackTrace(); } }
@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)); }
public Traversal.Admin<S, E> apply(final Graph graph) { try { final ScriptEngine engine = SingleGremlinScriptEngineManager.get(this.scriptEngineName); final Bindings engineBindings = engine.createBindings(); engineBindings.put("g", this.traversalSourceFactory.createTraversalSource(graph)); for (int i = 0; i < this.bindings.length; i = i + 2) { engineBindings.put((String) this.bindings[i], this.bindings[i + 1]); } final Traversal.Admin<S, E> traversal = (Traversal.Admin<S, E>) engine.eval(this.traversalScript, engineBindings); if (!traversal.isLocked()) traversal.applyStrategies(); return traversal; } catch (final ScriptException e) { throw new IllegalStateException(e.getMessage(), e); } }
/** * 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)); } }
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."); }
@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(); }
@Override public void handleAction( final Context context, final ActionRequest request, final Bindings handler) throws ResourceException { super.handleAction(context, request, handler); for (Map.Entry<String, String> entry : request.getAdditionalParameters().entrySet()) { if (handler.containsKey(entry.getKey())) { continue; } if (bindings != null) { bindings.put(entry.getKey(), entry.getValue()); } } handler.put("request", request); handler.put("resources", configuration.get("resources").copy().getObject()); }
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; }
@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(); }
/** Set parameters in bindings if any */ protected final void prepareBindings(Bindings bindings) { // add parameters if (this.parameters != null) { bindings.put(Script.ARGUMENTS_NAME, this.parameters); } // add special bindings this.prepareSpecialBindings(bindings); }
/** 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); } }
private Collection<Throwable> execute_fasta(String source) throws IOException { FastaIterator iter = new FastaIterator(); try { iter.in = (source == null ? IOUtils.openStdinForLineIterator() : IOUtils.openURIForLineIterator(source)); bindings.put("iter", iter); bindings.put("format", "fasta"); this.script.eval(bindings); return RETURN_OK; } catch (Exception e) { LOG.error(e); return wrapException(e); } finally { CloserUtil.close(iter.in); bindings.remove("iter"); bindings.remove("format"); } }
public Gauge getGauge(InputStream stream) { GeneralPath path = new GeneralPath(); GaugeFactoryAPI api = new GaugeFactoryAPI(); InputStreamReader reader = new InputStreamReader(stream); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByExtension("js"); Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("path", path); bindings.put("self", api); try { engine.eval(reader, bindings); } catch (Exception e) { e.printStackTrace(); } Gauge gauge = new Gauge(path, api.color); return gauge; }
public Object put(String name, Object value) { if (storeScriptVariables) { Object oldValue = null; if (!UNSTORED_KEYS.contains(name)) { oldValue = variableScope.getVariable(name); variableScope.setVariable(name, value); return oldValue; } } return defaultBindings.put(name, value); }