List of usage examples for javax.script SimpleBindings SimpleBindings
public SimpleBindings()
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@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();//from w w w .j a v a2s .co m }
From source file:org.jahia.services.content.rules.RulesNotificationService.java
private void sendMail(String template, Object user, String toMail, String fromMail, String ccList, String bcclist, Locale locale, KnowledgeHelper drools) throws RepositoryException, ScriptException, IOException { if (!notificationService.isEnabled()) { return;/*from w w w . j a v a 2 s . c o m*/ } if (StringUtils.isEmpty(toMail)) { logger.warn("A mail couldn't be sent because to: has no recipient"); return; } // Resolve template : String extension = StringUtils.substringAfterLast(template, "."); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension); ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); bindings.put("currentUser", user); bindings.put("contextPath", Jahia.getContextPath()); bindings.put("currentLocale", locale); final Object object = drools.getMatch().getTuple().getHandle().getObject(); JCRNodeWrapper node = null; if (object instanceof AbstractNodeFact) { node = ((AbstractNodeFact) object).getNode(); bindings.put("currentNode", node); final int siteURLPortOverride = SettingsBean.getInstance().getSiteURLPortOverride(); bindings.put("servername", "http" + (siteURLPortOverride == 443 ? "s" : "") + "://" + node.getResolveSite().getServerName() + ((siteURLPortOverride != 0 && siteURLPortOverride != 80 && siteURLPortOverride != 443) ? ":" + siteURLPortOverride : "")); } InputStream scriptInputStream = JahiaContextLoaderListener.getServletContext() .getResourceAsStream(template); if (scriptInputStream == null && node != null) { RulesListener rulesListener = RulesListener.getInstance(node.getSession().getWorkspace().getName()); String packageName = drools.getRule().getPackageName(); JahiaTemplateManagerService jahiaTemplateManagerService = ServicesRegistry.getInstance() .getJahiaTemplateManagerService(); for (Map.Entry<String, String> entry : rulesListener.getModulePackageNameMap().entrySet()) { if (packageName.equals(entry.getValue())) { JahiaTemplatesPackage templatePackage = jahiaTemplateManagerService .getTemplatePackage(entry.getKey()); Resource resource = templatePackage.getResource(template); if (resource != null) { scriptInputStream = resource.getInputStream(); break; } } } } if (scriptInputStream != null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); String subject = ""; try { ResourceBundle resourceBundle = ResourceBundles.get(resourceBundleName, locale); bindings.put("bundle", resourceBundle); subject = resourceBundle.getString("subject"); } catch (MissingResourceException e) { if (node != null) { final Value[] values = node.getResolveSite().getProperty("j:installedModules").getValues(); for (Value value : values) { try { ResourceBundle resourceBundle = ResourceBundles .get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackageById(value.getString()).getName(), locale); subject = resourceBundle.getString( drools.getRule().getName().toLowerCase().replaceAll(" ", ".") + ".subject"); bindings.put("bundle", resourceBundle); } catch (MissingResourceException ee) { // Do nothing } } } } Reader scriptContent = null; try { scriptContent = new InputStreamReader(scriptInputStream); scriptContext.setWriter(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(); String body = writer.toString(); notificationService.sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } }
From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java
/** * A generalized implementation of the "eval" operation. It handles script evaluation and iteration of results * so as to write {@link ResponseMessage} objects down the Netty pipeline. It also handles script timeouts, * iteration timeouts, metrics and building bindings. Note that result iteration is delegated to the * {@link #handleIterator} method, so those extending this class could override that method for better control * over result iteration./* w w w . j a v a 2 s . c o m*/ * * @param context The current Gremlin Server {@link Context} * @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the * script evaluation. * @param bindingsSupplier A function that returns the {@link Bindings} to provide to the * {@link GremlinExecutor#eval} method. */ protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier, final BindingSupplier bindingsSupplier) throws OpProcessorException { final Timer.Context timerContext = evalOpTimer.time(); final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final RequestMessage msg = context.getRequestMessage(); final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get(); final Settings settings = context.getSettings(); final Map<String, Object> args = msg.getArgs(); final String script = (String) args.get(Tokens.ARGS_GREMLIN); final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE) : null; final Bindings bindings = new SimpleBindings(); // sessionless requests are always transaction managed, but in-session requests are configurable. final boolean managedTransactionsForRequest = manageTransactions ? true : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false); final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build().beforeEval(b -> { try { b.putAll(bindingsSupplier.get()); } catch (OpProcessorException ope) { // this should bubble up in the GremlinExecutor properly as the RuntimeException will be // unwrapped and the root cause thrown throw new RuntimeException(ope); } }).withResult(o -> { final Iterator itty = IteratorUtils.asIterator(o); logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg, Thread.currentThread().getName()); try { handleIterator(context, itty); } catch (TimeoutException ex) { final String errorMessage = String.format( "Response iteration exceeded the configured threshold for request [%s] - %s", msg, ex.getMessage()); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } catch (Exception ex) { logger.warn(String.format("Exception processing a script on request [%s].", msg), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).create()); if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); } }).create(); final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle); evalFuture.handle((v, t) -> { timerContext.stop(); if (t != null) { if (t instanceof OpProcessorException) { ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage()); } else if (t instanceof TimedInterruptTimeoutException) { // occurs when the TimedInterruptCustomizerProvider is in play final String errorMessage = String.format( "A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider", msg); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage( "Timeout during script evaluation triggered by TimedInterruptCustomizerProvider") .create()); } else if (t instanceof TimeoutException) { final String errorMessage = String.format( "Response evaluation exceeded the configured threshold for request [%s] - %s", msg, t.getMessage()); logger.warn(errorMessage, t); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(t.getMessage()).create()); } else { logger.warn(String.format("Exception processing a script on request [%s].", msg), t); ctx.writeAndFlush( ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION) .statusMessage(t.getMessage()).create()); } } return null; }); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldOverrideBeforeEval() throws Exception { final AtomicInteger called = new AtomicInteger(0); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().beforeEval(b -> called.set(1)).create(); assertEquals(2, gremlinExecutor.eval("1+1", null, new SimpleBindings(), GremlinExecutor.LifeCycle.build().beforeEval(b -> called.set(200)).create()).get()); // need to wait long enough for the callback to register Thread.sleep(500);/* w w w. j av a 2s . c o m*/ assertEquals(200, called.get()); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
/** * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle. * * @param script the script to evaluate/*w w w .j a va 2 s . c o m*/ * @param language the language to evaluate it in * @param boundVars the bindings to evaluate in the context of the script * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process */ public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars, final LifeCycle lifeCycle) { final String lang = Optional.ofNullable(language).orElse("gremlin-groovy"); logger.debug("Preparing to evaluate script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); bindings.putAll(boundVars); final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>(); final FutureTask<Void> f = new FutureTask<>(() -> { try { lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings); logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName()); final Object o = scriptEngines.eval(script, bindings, lang); // apply a transformation before sending back the result - useful when trying to force serialization // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some // transactional constraints final Object result = lifeCycle.getTransformResult().isPresent() ? lifeCycle.getTransformResult().get().apply(o) : o; // a mechanism for taking the final result and doing something with it in the same thread, but // AFTER the eval and transform are done and that future completed. this provides a final means // for working with the result in the same thread as it was eval'd if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result); lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings); // the evaluationFuture must be completed after all processing as an exception in lifecycle events // that must raise as an exception to the caller who has the returned evaluationFuture. in other words, // if it occurs before this point, then the handle() method won't be called again if there is an // exception that ends up below trying to completeExceptionally() evaluationFuture.complete(result); } catch (Throwable ex) { final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex); // thread interruptions will typically come as the result of a timeout, so in those cases, // check for that situation and convert to TimeoutException if (root instanceof InterruptedException) evaluationFuture.completeExceptionally(new TimeoutException(String.format( "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s", scriptEvaluationTimeout, script, root.getMessage()))); else { lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root); evaluationFuture.completeExceptionally(root); } } return null; }); executorService.execute(f); if (scriptEvaluationTimeout > 0) { // Schedule a timeout in the thread pool for future execution final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> { logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName()); if (!f.isDone()) { lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings); f.cancel(true); } }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS); // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed // with exception evaluationFuture.handleAsync((v, t) -> { logger.debug( "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception)."); return sf.cancel(true); }); } return evaluationFuture; }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldOverrideAfterSuccess() throws Exception { final AtomicInteger called = new AtomicInteger(0); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterSuccess(b -> called.set(1)).create(); assertEquals(2,/* w w w .ja v a2 s. c o m*/ gremlinExecutor .eval("1+1", null, new SimpleBindings(), GremlinExecutor.LifeCycle.build().afterSuccess(b -> called.set(200)).create()) .get()); // need to wait long enough for the callback to register Thread.sleep(500); assertEquals(200, called.get()); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldOverrideAfterFailure() throws Exception { final AtomicInteger called = new AtomicInteger(0); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure((b, t) -> called.set(1)) .create();// ww w.ja v a 2 s. co m try { gremlinExecutor .eval("10/0", null, new SimpleBindings(), GremlinExecutor.LifeCycle.build().afterFailure((b, t) -> called.set(200)).create()) .get(); fail("Should have failed with division by zero"); } catch (Exception ignored) { } // need to wait long enough for the callback to register Thread.sleep(500); assertEquals(200, called.get()); }
From source file:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java
protected void initScriptContext() throws ScriptException { final Bindings oldEngineBindings = this.engine.getBindings(ScriptContext.ENGINE_SCOPE); final AMDModulePreloader oldPreloader = this.amdPreloader; final AMDScriptRunner oldAMDRunner = this.amdRunner; LOGGER.debug("Initializing new script context"); inEngineContextInitialization.set(Boolean.TRUE); try (NashornScriptModel model = NashornScriptModel.openModel()) { // create new (unpolluted) engine bindings final Bindings engineBindings = this.engine.createBindings(); this.engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE); final Bindings globalBindings = new SimpleBindings(); this.engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE); // only available during initialisation globalBindings.put("applicationContext", this.applicationContext); LOGGER.debug("Executing bootstrap scripts"); URL resource;//from w ww. ja va 2 s.co m // 1) simple logger facade for SLF4J LOGGER.debug("Bootstrapping simple logger"); resource = NashornScriptProcessor.class.getResource(SCRIPT_SIMPLE_LOGGER); this.executeScriptFromResource(resource); // 2) AMD loader and noSuchProperty to be used for all scripts apart from bootstrap LOGGER.debug("Setting up AMD"); resource = NashornScriptProcessor.class.getResource(SCRIPT_AMD); this.executeScriptFromResource(resource); resource = NashornScriptProcessor.class.getResource(SCRIPT_NO_SUCH_PROPERTY); this.executeScriptFromResource(resource); final Object define = this.engine.get("define"); this.amdPreloader = ((Invocable) this.engine).getInterface(define, AMDModulePreloader.class); // 3) the nashorn loader plugin so we can control access to globals LOGGER.debug("Setting up nashorn AMD loader"); this.preloadAMDModule("loaderMetaLoader", "nashorn", "nashorn"); // 4) remove Nashorn globals LOGGER.debug("Removing disallowed Nashorn globals \"{}\" and \"{}\"", NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE, this.nashornGlobalPropertiesToRemove); for (final String property : NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE) { engineBindings.remove(property); } if (this.nashornGlobalPropertiesToRemove != null) { for (final String property : this.nashornGlobalPropertiesToRemove.split(",")) { engineBindings.remove(property.trim()); } } // 5) Java extensions (must be picked up by modules before #9) globalBindings.put("processorExtensions", this.processorExtensions); // 6) AMD config LOGGER.debug("Applying AMD config \"{}\"", this.amdConfig); resource = this.amdConfig.getURL(); this.executeScriptFromResource(resource); // 7) configured JavaScript base modules LOGGER.debug("Bootstrapping base modules"); this.initScriptContextBaseModules(this.amdPreloader); // 8) configured JavaScript extension modules LOGGER.debug("Bootstrapping extension modules"); this.initScriptContextExtensions(this.amdPreloader); // 9) remove any init data that shouldn't be publicly available globalBindings.clear(); // 10) obtain the runner interface LOGGER.debug("Preparing AMD script runner"); resource = NashornScriptProcessor.class.getResource(SCRIPE_AMD_SCRIPT_RUNNER); final Object scriptRunnerObj = this.executeScriptFromResource(resource); this.amdRunner = ((Invocable) this.engine).getInterface(scriptRunnerObj, AMDScriptRunner.class); LOGGER.info("New script context initialized"); } catch (final Throwable t) { LOGGER.warn("Initialization of script context failed", t); // reset this.engine.setBindings(oldEngineBindings, ScriptContext.ENGINE_SCOPE); this.engine.getBindings(ScriptContext.GLOBAL_SCOPE).clear(); this.amdPreloader = oldPreloader; this.amdRunner = oldAMDRunner; if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof ScriptException) { throw (ScriptException) t; } else { throw new org.alfresco.scripts.ScriptException( "Unknown error initializing script context - reset to previous state", t); } } finally { inEngineContextInitialization.remove(); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
@Override public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource) throws ScriptException { // these validations occur before merging in bytecode bindings which will override existing ones. need to // extract the named traversalsource prior to that happening so that bytecode bindings can share the same // namespace as global bindings (e.g. traversalsources and graphs). if (traversalSource.equals(HIDDEN_G)) throw new IllegalArgumentException( "The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved"); if (bindings.containsKey(HIDDEN_G)) throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved"); if (!bindings.containsKey(traversalSource)) throw new IllegalArgumentException( "The bindings available to the ScriptEngine do not contain a traversalSource named: " + traversalSource); final Object b = bindings.get(traversalSource); if (!(b instanceof TraversalSource)) throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName() + " and is not an instance of TraversalSource"); final Bindings inner = new SimpleBindings(); inner.putAll(bindings);// ww w . ja v a2s .c o m inner.putAll(bytecode.getBindings()); inner.put(HIDDEN_G, b); return (Traversal.Admin) this.eval(GroovyTranslator.of(HIDDEN_G).translate(bytecode), inner); }