List of usage examples for javax.script ScriptEngine getContext
public ScriptContext getContext();
ScriptContext
of the ScriptEngine
whose Bindings, Reader and Writers are used for script executions when no ScriptContext
is specified. From source file:org.rhq.enterprise.server.plugins.alertScriptlang.ScriptLangSender.java
@Override public SenderResult send(Alert alert) { String scriptName = alertParameters.getSimpleValue("name", null); if (scriptName == null) { return new SenderResult(ResultState.FAILURE, "No script given"); }//from w w w . j a va 2 s .c o m String language = alertParameters.getSimpleValue("language", "jruby"); ScriptEngine engine = pluginComponent.getEngineByLanguage(language); // ScriptEngineManager manager = new ScriptEngineManager(serverPluginEnvironment.getPluginClassLoader()); // engine = manager.getEngineByName(language); if (engine == null) { return new SenderResult(ResultState.FAILURE, "Script engine with name [" + language + "] does not exist"); } File file = new File(pluginComponent.baseDir + scriptName); if (!file.exists() || !file.canRead()) { return new SenderResult(ResultState.FAILURE, "Script [" + scriptName + "] does not exist or is not readable at [" + file.getAbsolutePath() + "]"); } Object result; try { BufferedReader br = new BufferedReader(new FileReader(file)); Map<String, String> preferencesMap = new HashMap<String, String>(); for (String key : preferences.getSimpleProperties().keySet()) preferencesMap.put(key, preferences.getSimple(key).getStringValue()); Map<String, String> parameterMap = new HashMap<String, String>(); for (String key : alertParameters.getSimpleProperties().keySet()) parameterMap.put(key, alertParameters.getSimple(key).getStringValue()); ScriptContext sc = engine.getContext(); sc.setAttribute("alertPreferences", preferencesMap, ScriptContext.ENGINE_SCOPE); sc.setAttribute("alertParameters", parameterMap, ScriptContext.ENGINE_SCOPE); engine.eval(br); AlertManagerLocal alertManager = LookupUtil.getAlertManager(); Object[] args = new Object[3]; args[0] = alert; args[1] = alertManager.prettyPrintAlertURL(alert); args[2] = alertManager.prettyPrintAlertConditions(alert, false); result = ((Invocable) engine).invokeFunction("sendAlert", args); if (result == null) { return new SenderResult(ResultState.FAILURE, "Script ]" + scriptName + "] returned null, so success is unknown"); } if (result instanceof SenderResult) return (SenderResult) result; return new SenderResult(ResultState.SUCCESS, "Sending via script resulted in " + result.toString()); } catch (Exception e) { e.printStackTrace(); return new SenderResult(ResultState.FAILURE, "Sending via [" + scriptName + "] failed: " + e.getMessage()); } }
From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java
/** * Get resources//w w w . ja v a2s . co m * * @param key * @param locale * @param site * @param jahiaUser * @return */ private String getResources(String key, Locale locale, JCRSiteNode site, JahiaUser jahiaUser) { if (key == null || key.length() == 0) { return key; } if (logger.isDebugEnabled()) { logger.debug("Resources key: " + key); } String baseName = null; String value = null; if (key.contains("@")) { baseName = StringUtils.substringAfter(key, "@"); key = StringUtils.substringBefore(key, "@"); } value = Messages.get(baseName, site != null ? site.getTemplatePackage() : null, key, locale, null); if (value == null || value.length() == 0) { value = Messages.getInternal(key, locale); } if (logger.isDebugEnabled()) { logger.debug("Resources value: " + value); } if (value.contains("${")) { try { ScriptEngine scriptEngine = scriptEngineUtils.getEngineByName("velocity"); ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); bindings.put("currentSite", site); bindings.put("currentUser", jahiaUser); bindings.put("currentLocale", locale); bindings.put("PrincipalViewHelper", PrincipalViewHelper.class); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(value, scriptContext); //String error = scriptContext.getErrorWriter().toString(); return scriptContext.getWriter().toString().trim(); } catch (ScriptException e) { logger.error("Error while executing script [" + value + "]", e); } } return value; }
From source file:org.labkey.nashorn.NashornController.java
private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine; ScriptContext context;//ww w. ja v a 2 s. c om Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() { @Override @NotNull public ScriptEngine call() throws Exception { NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" }); return engine; } }; if (useSession) { HttpServletRequest req = getViewContext().getRequest(); engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext); } else { engine = createContext.call(); } Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE); engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext())); Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE); // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine // some docs mention enginScope.get("nashorn.global"), but that is also null if (null == globalScope) globalScope = (Bindings) engineScope.get("nashorn.global"); if (null == globalScope) globalScope = engineScope; globalScope.put("console", new Console()); return new Pair<>(engine, engine.getContext()); }
From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { log.info("Loading Script: " + file.getAbsolutePath()); }//from w w w . j a v a 2 s . c o m if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { _log.info("Loading Script: " + file.getAbsolutePath()); }/* ww w . j av a 2 s . co m*/ if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
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// www.j a v a 2s. 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; }
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 ww w.j a v a 2 s.c om*/ 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.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 ww. j a va2s .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); } } } }