List of usage examples for javax.script Bindings put
public Object put(String name, Object value);
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java
@Test public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine( new InterpreterModeCustomizerProvider()); final Bindings b = new SimpleBindings(); b.put("x", 2); engine.eval("def addItUp = { x, y -> x + y }", b); assertEquals(3, engine.eval("int xxx = 1 + x", b)); assertEquals(4, engine.eval("yyy = xxx + 1", b)); assertEquals(7, engine.eval("def zzz = yyy + xxx", b)); assertEquals(4, engine.eval("zzz - xxx", b)); assertEquals("accessible-globally", engine.eval( "if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b)); assertEquals("accessible-globally", engine.eval("outer", b)); try {//from ww w . j a va2 s . co m engine.eval("inner", b); fail("Should not have been able to access 'inner'"); } catch (Exception ex) { final Throwable root = ExceptionUtils.getRootCause(ex); assertThat(root, instanceOf(MissingPropertyException.class)); } assertEquals(10, engine.eval("addItUp(zzz,xxx)", b)); }
From source file:org.mule.module.scripting.component.Scriptable.java
private void populateVariablesInOrder(Bindings bindings, MuleMessage message) { for (String key : message.getSessionPropertyNames()) { bindings.put(key, message.getSessionProperty(key)); }/* w w w . j av a 2 s .c o m*/ for (String key : message.getInvocationPropertyNames()) { bindings.put(key, message.getInvocationProperty(key)); } }
From source file:org.mule.module.scripting.component.Scriptable.java
public void populateDefaultBindings(Bindings bindings) { if (properties != null) { bindings.putAll((Map) properties); }/*from w w w. jav a2s .com*/ bindings.put("log", logger); // A place holder for a returned result if the script doesn't return a result. // The script can overwrite this binding bindings.put("result", NullPayload.getInstance()); bindings.put("muleContext", muleContext); bindings.put("registry", muleContext.getRegistry()); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineTest.java
@Test public void shouldAllowVariableReuseAcrossThreads() throws Exception { final BasicThreadFactory testingThreadFactory = new BasicThreadFactory.Builder() .namingPattern("test-gremlin-scriptengine-%d").build(); final ExecutorService service = Executors.newFixedThreadPool(8, testingThreadFactory); final GremlinGroovyScriptEngine scriptEngine = new GremlinGroovyScriptEngine(); final AtomicBoolean failed = new AtomicBoolean(false); final int max = 512; final List<Pair<Integer, List<Integer>>> futures = Collections.synchronizedList(new ArrayList<>(max)); IntStream.range(0, max).forEach(i -> { final int yValue = i * 2; final int zValue = i * -1; final Bindings b = new SimpleBindings(); b.put("x", i); b.put("y", yValue); final String script = "z=" + zValue + ";[x,y,z]"; try {/* w w w.j a v a 2 s . c o m*/ service.submit(() -> { try { final List<Integer> result = (List<Integer>) scriptEngine.eval(script, b); futures.add(Pair.with(i, result)); } catch (Exception ex) { failed.set(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } }); service.shutdown(); assertThat(service.awaitTermination(120000, TimeUnit.MILLISECONDS), is(true)); // likely a concurrency exception if it occurs - and if it does then we've messed up because that's what this // test is partially designed to protected against. assertThat(failed.get(), is(false)); assertEquals(max, futures.size()); futures.forEach(t -> { assertEquals(t.getValue0(), t.getValue1().get(0)); assertEquals(t.getValue0() * 2, t.getValue1().get(1).intValue()); assertEquals(t.getValue0() * -1, t.getValue1().get(2).intValue()); }); }
From source file:org.ms123.common.utils.UtilsServiceImpl.java
public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception { System.out.println("UtilsServiceImpl.executeScript:" + params); String storeId = (String) params.get("storeId"); StoreDesc sdesc = StoreDesc.get(storeId); namespace = sdesc.getNamespace();//from w ww . ja v a 2s . com System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace); ScriptEngine se = m_scriptEngineService.getEngineByName("groovy"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); se.getContext().setWriter(pw); Bindings b = se.createBindings(); b.putAll(params); b.put("jdo", m_dataLayer); b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService")); b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService")); b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService")); b.put("storeDesc", sdesc); b.put("home", System.getProperty("simpl4.dir")); b.put("log", m_logger); b.put("user", user); b.put("namespace", namespace); se.setBindings(b, ScriptContext.ENGINE_SCOPE); b.put("se", se); Object r = ""; FileReader fr = getScriptFile(namespace, scriptName); r = se.eval(fr); System.out.println("r:" + r); pw.close(); m_logger.info("executeScript:" + sw); System.out.println("executeScript:" + sw); return null; }
From source file:ru.iris.events.EventsService.java
public EventsService() { Status status = new Status("Events"); if (status.checkExist()) { status.running();//from w ww . j a v a 2 s . c om } else { status.addIntoDB("Events", "Service that listen for events and exec scripts as needed"); } try { events = Ebean.find(Event.class).findList(); // take pause to save/remove new entity try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // load all scripts, compile and put into map compiledScriptMap = loadAndCompile(events); // Pass jsonmessaging instance to js engine Bindings bindings = new SimpleBindings(); bindings.put("jsonMessaging", jsonMessaging); bindings.put("LOGGER", scriptLogger); // subscribe to events from db for (Event event : events) { jsonMessaging.subscribe(event.getSubject()); LOGGER.debug("Subscribe to subject: " + event.getSubject()); } // command launch jsonMessaging.subscribe("event.command"); // scripts jsonMessaging.subscribe("event.script.get"); jsonMessaging.subscribe("event.script.save"); jsonMessaging.subscribe("event.script.delete"); jsonMessaging.subscribe("event.script.list"); jsonMessaging.subscribe("event.reload"); jsonMessaging.setNotification(new JsonNotification() { @Override public void onNotification(JsonEnvelope envelope) { LOGGER.debug("Got envelope with subject: " + envelope.getSubject()); try { // Get script content if (envelope.getObject() instanceof EventGetScriptAdvertisement) { LOGGER.debug("Return JS script to: " + envelope.getReceiverInstance()); EventGetScriptAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); jsonMessaging.response(envelope, new EventResponseGetScriptAdvertisement(FileUtils.readFileToString(jsFile))); } // Save new/existing script else if (envelope.getObject() instanceof EventResponseSaveScriptAdvertisement) { EventResponseSaveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to save changes: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.writeStringToFile(jsFile, advertisement.getBody()); LOGGER.info("Restart event service (reason: script change)"); reloadService(); } // Remove script else if (envelope.getObject() instanceof EventRemoveScriptAdvertisement) { EventRemoveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to remove script: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.forceDelete(jsFile); LOGGER.info("Restart event service (reason: script removed)"); reloadService(); } // List available scripts else if (envelope.getObject() instanceof EventListScriptsAdvertisement) { EventListScriptsAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/"); else jsFile = new File("./scripts/"); EventResponseListScriptsAdvertisement response = new EventResponseListScriptsAdvertisement(); response.setScripts( (List<File>) FileUtils.listFiles(jsFile, new String[] { "js" }, false)); jsonMessaging.response(envelope, response); } // Check command and launch script else if (envelope.getObject() instanceof CommandAdvertisement) { CommandAdvertisement advertisement = envelope.getObject(); bindings.put("advertisement", envelope.getObject()); if (compiledCommandScriptMap.get(advertisement.getScript()) == null) { LOGGER.debug("Compile command script: " + advertisement.getScript()); File jsFile = new File("./scripts/command/" + advertisement.getScript()); CompiledScript compile = engine.compile(FileUtils.readFileToString(jsFile)); compiledCommandScriptMap.put(advertisement.getScript(), compile); LOGGER.debug("Launch compiled command script: " + advertisement.getScript()); compile.eval(bindings); } else { LOGGER.info("Launch compiled command script: " + advertisement.getScript()); compiledCommandScriptMap.get(advertisement.getScript()).eval(bindings); } } else if (envelope.getObject() instanceof EventChangesAdvertisement) { reloadService(); } else { for (Event event : events) { if (envelope.getSubject().equals(event.getSubject()) || wildCardMatch(event.getSubject(), envelope.getSubject())) { LOGGER.debug("Run compiled script: " + event.getScript()); try { bindings.put("advertisement", envelope.getObject()); CompiledScript script = compiledScriptMap.get(event.getScript()); if (script != null) script.eval(bindings); else LOGGER.error("Error! Script " + event.getScript() + " is NULL!"); } catch (ScriptException e) { LOGGER.error("Error in script scripts/command/" + event.getScript() + ": " + e.toString()); e.printStackTrace(); } } } } } catch (ScriptException | IOException e) { LOGGER.error("Error in script: " + e.toString()); e.printStackTrace(); } } }); jsonMessaging.start(); } catch (final RuntimeException t) { LOGGER.error("Error in Events!"); status.crashed(); t.printStackTrace(); } }
From source file:com.netflix.genie.web.services.loadbalancers.script.ScriptLoadBalancer.java
/** * {@inheritDoc}//from w w w . j a va 2s . c o m */ @Override public Cluster selectCluster(@Nonnull @NonNull @NotEmpty final Set<Cluster> clusters, @Nonnull @NonNull final JobRequest jobRequest) throws GenieException { final long selectStart = System.nanoTime(); log.debug("Called"); final Set<Tag> tags = Sets.newHashSet(); try { if (this.isConfigured.get() && this.script.get() != null) { log.debug("Evaluating script for job {}", jobRequest.getId().orElse("without id")); final Bindings bindings = new SimpleBindings(); // TODO: For now for backwards compatibility with balancer scripts continue writing Clusters out in // V3 format. Change to V4 once stabalize a bit more bindings.put(CLUSTERS_BINDING, this.mapper.writeValueAsString( clusters.stream().map(DtoConverters::toV3Cluster).collect(Collectors.toSet()))); bindings.put(JOB_REQUEST_BINDING, this.mapper.writeValueAsString(jobRequest)); // Run as callable and timeout after the configured timeout length final String clusterId = this.asyncTaskExecutor .submit(() -> (String) this.script.get().eval(bindings)) .get(this.timeoutLength.get(), TimeUnit.MILLISECONDS); // Find the cluster if not null if (clusterId != null) { for (final Cluster cluster : clusters) { if (clusterId.equals(cluster.getId())) { tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FOUND)); return cluster; } } } log.warn("Script returned a cluster not in the input list: {}", clusterId); } else { log.debug("Script returned null"); tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_NOT_CONFIGURED)); return null; } tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_NOT_FOUND)); // Defer to any subsequent load balancer in the chain return null; } catch (final Exception e) { tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FAILED)); tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, e.getClass().getCanonicalName())); log.error("Unable to execute script due to {}", e.getMessage(), e); return null; } finally { this.registry.timer(SELECT_TIMER_NAME, tags).record(System.nanoTime() - selectStart, TimeUnit.NANOSECONDS); } }
From source file:org.jahia.services.render.scripting.JSR223Script.java
/** * Execute the script and return the result as a string * * @param resource resource to display/* w w w .j av a 2 s .c o m*/ * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException */ public String execute(Resource resource, RenderContext context) throws RenderException { ScriptEngine scriptEngine = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader()); try { scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension()); if (scriptEngine != null) { ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames(); while (attrNamesEnum.hasMoreElements()) { String currentAttributeName = (String) attrNamesEnum.nextElement(); if (!"".equals(currentAttributeName)) { bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName)); } } bindings.put("params", context.getRequest().getParameterMap()); Reader scriptContent = null; try { InputStream scriptInputStream = getViewInputStream(); if (scriptInputStream != null) { scriptContent = new InputStreamReader(scriptInputStream); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); return writer.toString().trim(); } else { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath()); } } catch (ScriptException e) { throw new RenderException("Error while executing script " + view.getPath(), e); } catch (IOException e) { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath(), e); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } } catch (ScriptException e) { logger.error(e.getMessage(), e); } finally { Thread.currentThread().setContextClassLoader(tccl); } return null; }