List of usage examples for javax.script SimpleBindings SimpleBindings
public SimpleBindings()
From source file:org.jahia.services.mail.MailServiceImpl.java
@Override public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail, String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName) throws RepositoryException, ScriptException { // Resolve template : ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, ".")); ScriptContext scriptContext = new SimpleScriptContext(); //try if it is multilingual String suffix = StringUtils.substringAfterLast(template, "."); String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_" + locale.toString() + "." + suffix; JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName); Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate); if (templateRealPath == null) { templateRealPath = templatePackage.getResource(template); }/*from www . j a v a 2 s . c o m*/ InputStream scriptInputStream = null; try { scriptInputStream = templateRealPath.getInputStream(); } catch (IOException e) { logger.error(e.getMessage(), e); } if (scriptInputStream != null) { ResourceBundle resourceBundle; if (templatePackageName == null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); resourceBundle = ResourceBundles.get(resourceBundleName, locale); } else { resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackage(templatePackageName), locale); } final Bindings bindings = new SimpleBindings(); bindings.put("bundle", resourceBundle); bindings.putAll(boundObjects); Reader scriptContent = null; // Subject String subject; try { String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, "."); InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream(); scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset) : new InputStreamReader(stream); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptEngine.eval(scriptContent, scriptContext); subject = scriptContext.getWriter().toString().trim(); } catch (Exception e) { logger.warn("Not able to render mail subject using " + StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, ".") + " template file - set org.jahia.services.mail.MailService in debug for more information"); if (logger.isDebugEnabled()) { logger.debug("generating the mail subject throw an exception : ", e); } subject = resourceBundle.getString( StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".") + ".subject"); } finally { IOUtils.closeQuietly(scriptContent); } try { try { scriptContent = templateCharset != null ? new InputStreamReader(scriptInputStream, templateCharset) : new InputStreamReader(scriptInputStream); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } 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); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); String body = writer.toString(); sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { IOUtils.closeQuietly(scriptContent); } } else { logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName + "] not found"); } }
From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java
private Bindings createBindings(final Map<String, Object> bindingMap, final Map<String, String> rebindingMap) { final Bindings bindings = new SimpleBindings(); // rebind any global bindings to a different variable. if (!rebindingMap.isEmpty()) { for (Map.Entry<String, String> kv : rebindingMap.entrySet()) { boolean found = false; final Map<String, Graph> graphs = this.graphManager.getGraphs(); if (graphs.containsKey(kv.getValue())) { bindings.put(kv.getKey(), graphs.get(kv.getValue())); found = true;/*from ww w .j a v a 2 s . c o m*/ } if (!found) { final Map<String, TraversalSource> traversalSources = this.graphManager.getTraversalSources(); if (traversalSources.containsKey(kv.getValue())) { bindings.put(kv.getKey(), traversalSources.get(kv.getValue())); found = true; } } if (!found) { final String error = String.format( "Could not rebind [%s] to [%s] as [%s] not in the Graph or TraversalSource global bindings", kv.getKey(), kv.getValue(), kv.getValue()); throw new IllegalStateException(error); } } } bindings.putAll(bindingMap); return bindings; }
From source file:org.jahia.osgi.FrameworkService.java
private void updateFileReferencesIfNeeded() { File script = new File( SettingsBean.getInstance().getJahiaVarDiskPath() + "/scripts/groovy/updateFileReferences.groovy"); if (!script.isFile()) { return;// ww w .j ava2 s . c o m } ScriptEngine scriptEngine; try { scriptEngine = ScriptEngineUtils.getInstance() .scriptEngine(FilenameUtils.getExtension(script.getName())); } catch (ScriptException e) { throw new JahiaRuntimeException(e); } if (scriptEngine == null) { throw new IllegalStateException("No script engine available"); } ScriptContext scriptContext = new SimpleScriptContext(); Bindings bindings = new SimpleBindings(); bindings.put("log", logger); bindings.put("logger", logger); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); try (FileInputStream scriptInputStream = new FileInputStream(script); InputStreamReader scriptReader = new InputStreamReader(scriptInputStream, Charsets.UTF_8); StringWriter out = new StringWriter()) { scriptContext.setWriter(out); scriptEngine.eval(scriptReader, scriptContext); } catch (ScriptException | IOException e) { throw new JahiaRuntimeException(e); } }
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 {/*from w ww . jav a 2 s . co 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.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
/** * Create bindings to be used by this {@code ScriptEngine}. In this case, {@link SimpleBindings} are returned. *//*from w ww . j a va2s . c om*/ @Override public Bindings createBindings() { return new SimpleBindings(); }
From source file:org.nuxeo.ecm.webengine.DefaultWebContext.java
public Bindings createBindings(Map<String, Object> vars) { Bindings bindings = new SimpleBindings(); if (vars != null) { bindings.putAll(vars);//from ww w . j ava2 s . com } initDefaultBindings(bindings); return bindings; }
From source file:org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor.java
private void iterateBytecodeTraversal(final Context context) throws Exception { final RequestMessage msg = context.getRequestMessage(); logger.debug("Traversal request {} for in thread {}", msg.getRequestId(), Thread.currentThread().getName()); // right now the TraversalOpProcessor can take a direct GraphSON representation of Bytecode or directly take // deserialized Bytecode object. final Object bytecodeObj = msg.getArgs().get(Tokens.ARGS_GREMLIN); final Bytecode bytecode = bytecodeObj instanceof Bytecode ? (Bytecode) bytecodeObj : mapper.readValue(bytecodeObj.toString(), Bytecode.class); // earlier validation in selection of this op method should free us to cast this without worry final Map<String, String> aliases = (Map<String, String>) msg.optionalArgs(Tokens.ARGS_ALIASES).get(); final GraphManager graphManager = context.getGraphManager(); final String traversalSourceName = aliases.entrySet().iterator().next().getValue(); final TraversalSource g = graphManager.getTraversalSource(traversalSourceName); final Traversal.Admin<?, ?> traversal; try {//ww w . ja va2 s . c om final Optional<String> lambdaLanguage = BytecodeHelper.getLambdaLanguage(bytecode); if (!lambdaLanguage.isPresent()) traversal = JavaTranslator.of(g).translate(bytecode); else { final SimpleBindings b = new SimpleBindings(); b.put(Tokens.VAL_TRAVERSAL_SOURCE_ALIAS, g); traversal = context.getGremlinExecutor().eval(bytecode, b, lambdaLanguage.get()); } } catch (Exception ex) { logger.error("Could not deserialize the Traversal instance", context); throw new OpProcessorException("Could not deserialize the Traversal instance", ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); } final Timer.Context timerContext = traversalOpTimer.time(); try { final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final Graph graph = g.getGraph(); context.getGremlinExecutor().getExecutorService().submit(() -> { try { beforeProcessing(graph, context); try { // compile the traversal - without it getEndStep() has nothing in it traversal.applyStrategies(); handleIterator(context, new TraverserIterator(traversal), graph); } catch (TimeoutException ex) { final String errorMessage = String.format( "Response iteration exceeded the configured threshold for request [%s] - %s", msg.getRequestId(), ex.getMessage()); logger.warn(errorMessage); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT) .statusMessage(errorMessage).statusAttributeException(ex).create()); onError(graph, context); return; } catch (Exception ex) { logger.warn(String.format("Exception processing a Traversal on iteration for request [%s].", msg.getRequestId()), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); onError(graph, context); return; } } catch (Exception ex) { logger.warn( String.format("Exception processing a Traversal on request [%s].", msg.getRequestId()), ex); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(ex.getMessage()).statusAttributeException(ex).create()); onError(graph, context); } finally { timerContext.stop(); } }); } catch (Exception ex) { timerContext.stop(); throw new OpProcessorException("Could not iterate the Traversal instance", ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR).statusMessage(ex.getMessage()) .statusAttributeException(ex).create()); } }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java
private ScriptEngines createScriptEngines() { // plugins already on the path - ones static to the classpath final List<GremlinPlugin> globalPlugins = new ArrayList<>(); ServiceLoader.load(GremlinPlugin.class).forEach(globalPlugins::add); return new ScriptEngines(se -> { // this first part initializes the scriptengines Map for (Map.Entry<String, EngineSettings> config : settings.entrySet()) { final String language = config.getKey(); se.reload(language, new HashSet<>(config.getValue().getImports()), new HashSet<>(config.getValue().getStaticImports()), config.getValue().getConfig()); }/*from w w w . j a v a 2 s.c o m*/ // use grabs dependencies and returns plugins to load final List<GremlinPlugin> pluginsToLoad = new ArrayList<>(globalPlugins); use.forEach(u -> { if (u.size() != 3) logger.warn( "Could not resolve dependencies for [{}]. Each entry for the 'use' configuration must include [groupId, artifactId, version]", u); else { logger.info("Getting dependencies for [{}]", u); pluginsToLoad.addAll(se.use(u.get(0), u.get(1), u.get(2))); } }); // now that all dependencies are in place, the imports can't get messed up if a plugin tries to execute // a script (as the script engine appends the import list to the top of all scripts passed to the engine). // only enable those plugins that are configured to be enabled. se.loadPlugins(pluginsToLoad.stream().filter(plugin -> enabledPlugins.contains(plugin.getName())) .collect(Collectors.toList())); // initialization script eval can now be performed now that dependencies are present with "use" for (Map.Entry<String, EngineSettings> config : settings.entrySet()) { final String language = config.getKey(); // script engine initialization files that fail will only log warnings - not fail server initialization final AtomicBoolean hasErrors = new AtomicBoolean(false); config.getValue().getScripts().stream().map(File::new).filter(f -> { if (!f.exists()) { logger.warn("Could not initialize {} ScriptEngine with {} as file does not exist", language, f); hasErrors.set(true); } return f.exists(); }).map(f -> { try { return Pair.with(f, Optional.of(new FileReader(f))); } catch (IOException ioe) { logger.warn("Could not initialize {} ScriptEngine with {} as file could not be read - {}", language, f, ioe.getMessage()); hasErrors.set(true); return Pair.with(f, Optional.<FileReader>empty()); } }).filter(p -> p.getValue1().isPresent()).map(p -> Pair.with(p.getValue0(), p.getValue1().get())) .forEachOrdered(p -> { try { final Bindings bindings = new SimpleBindings(); bindings.putAll(globalBindings); // evaluate init scripts with hard reference so as to ensure it doesn't get garbage collected bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE, GremlinGroovyScriptEngine.REFERENCE_TYPE_HARD); // the returned object should be a Map of initialized global bindings final Object initializedBindings = se.eval(p.getValue1(), bindings, language); if (initializedBindings != null && initializedBindings instanceof Map) globalBindings.putAll((Map) initializedBindings); else logger.warn( "Initialization script {} did not return a Map - no global bindings specified", p.getValue0()); logger.info("Initialized {} ScriptEngine with {}", language, p.getValue0()); } catch (ScriptException sx) { hasErrors.set(true); logger.warn( "Could not initialize {} ScriptEngine with {} as script could not be evaluated - {}", language, p.getValue0(), sx.getMessage()); } }); } }); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldAllowVariableReuseAcrossThreads() throws Exception { final ExecutorService service = Executors.newFixedThreadPool(8, testingThreadFactory); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); 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 Bindings b = new SimpleBindings(); b.put("x", i); b.put("y", yValue); final int zValue = i * -1; final String script = "z=" + zValue + ";[x,y,z]"; try {/*from w ww . java2 s . co m*/ service.submit(() -> { try { final List<Integer> result = (List<Integer>) gremlinExecutor.eval(script, b).get(); futures.add(Pair.with(i, result)); } catch (Exception ex) { failed.set(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } }); service.shutdown(); assertThat(service.awaitTermination(60000, 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.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldAllowConcurrentModificationOfGlobals() throws Exception { // this test simulates a scenario that likely shouldn't happen - where globals are modified by multiple // threads. globals are created in a synchronized fashion typically but it's possible that someone // could do something like this and this test validate that concurrency exceptions don't occur as a // result//from ww w .ja v a2 s .com final ExecutorService service = Executors.newFixedThreadPool(8, testingThreadFactory); final Bindings globals = new SimpleBindings(); globals.put("g", -1); final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(globals).create(); 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 Bindings b = new SimpleBindings(); b.put("x", i); b.put("y", yValue); final int zValue = i * -1; final String script = "z=" + zValue + ";[x,y,z,g]"; try { service.submit(() -> { try { // modify the global in a separate thread gremlinExecutor.getGlobalBindings().put("g", i); gremlinExecutor.getGlobalBindings().put(Integer.toString(i), i); gremlinExecutor.getGlobalBindings().keySet().stream() .filter(s -> i % 2 == 0 && !s.equals("g")).findFirst().ifPresent(globals::remove); final List<Integer> result = (List<Integer>) gremlinExecutor.eval(script, b).get(); futures.add(Pair.with(i, result)); } catch (Exception ex) { failed.set(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); } }); service.shutdown(); assertThat(service.awaitTermination(60000, 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()); assertThat(t.getValue1().get(3).intValue(), greaterThan(-1)); }); }