Java Code Examples for org.apache.velocity.context.Context#put()
The following examples show how to use
org.apache.velocity.context.Context#put() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VelocityContainerRenderer.java From olat with Apache License 2.0 | 6 votes |
/** * org.olat.presentation.framework.components.Component, org.olat.presentation.framework.render.URLBuilder, org.olat.presentation.framework.translator.Translator, * org.olat.presentation.framework.render.RenderResult, java.lang.String[]) */ @Override public void render(Renderer renderer, StringOutput target, Component source, URLBuilder ubu, Translator translator, RenderResult renderResult, String[] args) { VelocityContainer vc = (VelocityContainer) source; String pagePath = vc.getPage(); Context ctx = vc.getContext(); // the component id of the urlbuilder will be overwritten by the recursive render call for // subcomponents (see Renderer) Renderer fr = Renderer.getInstance(vc, translator, ubu, renderResult, renderer.getGlobalSettings()); VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc); ctx.put("r", vrdec); String mm = velocityHelper.mergeContent(pagePath, ctx, theme); // experimental!!! // surround with red border if recording mark indicates so. if (vc.markingCommandString != null) { target.append("<table style=\"border:3px solid red; background-color:#E0E0E0; padding:4px; margin:0px;\"><tr><td>").append(mm).append("</td></tr></table>"); } else { target.append(mm); } }
Example 2
Source File: TACourseNodeEditController.java From olat with Apache License 2.0 | 6 votes |
private String getTaskDeletedMailBody(final UserRequest ureq, final String fileName, final String courseName, final String courseLink) { // grab standard text final String confirmation = translate("task.deleted.body"); final Context c = new VelocityContext(); final Identity identity = ureq.getIdentity(); c.put("login", identity.getName()); c.put("first", getUserService().getUserProperty(identity.getUser(), UserConstants.FIRSTNAME, getLocale())); c.put("last", getUserService().getUserProperty(identity.getUser(), UserConstants.LASTNAME, getLocale())); c.put("email", getUserService().getUserProperty(identity.getUser(), UserConstants.EMAIL, getLocale())); c.put("filename", fileName); c.put("coursename", courseName); c.put("courselink", courseLink); final VelocityHelper vh = (VelocityHelper) CoreSpringFactory.getBean(VelocityHelper.class); return vh.evaluateVTL(confirmation, c); }
Example 3
Source File: VelocityView.java From scoold with Apache License 2.0 | 6 votes |
/** * Expose the tool attributes, according to corresponding bean property settings. * <p> * Do not override this method unless for further tools driven by bean properties. Override one of the * {@code exposeHelpers} methods to add custom helpers. * * @param velocityContext Velocity context that will be passed to the template * @param request current HTTP request * @throws Exception if there's a fatal error while we're adding model attributes */ protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception { // Expose generic attributes. if (this.toolAttributes != null) { for (Map.Entry<String, Class<?>> entry : this.toolAttributes.entrySet()) { String attributeName = entry.getKey(); Class<?> toolClass = entry.getValue(); try { Object tool = toolClass.getDeclaredConstructor().newInstance(); initTool(tool, velocityContext); velocityContext.put(attributeName, tool); } catch (Exception ex) { throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex); } } } }
Example 4
Source File: Test2.java From java-course-ee with MIT License | 6 votes |
public Test2() throws Exception { //init Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties"); // get Template Template template = Velocity.getTemplate("Test2.vm"); // getContext Context context = new VelocityContext(); String name = "Vova"; context.put("name", name); // get Writer Writer writer = new StringWriter(); // merge template.merge(context, writer); System.out.println(writer.toString()); }
Example 5
Source File: TestServlet.java From java-course-ee with MIT License | 6 votes |
@Override public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) { if (request.getParameter("submit") != null) { List<String> errors = new ArrayList(); String name = request.getParameter("name"); System.out.println("name = " + name); try { double price = Double.parseDouble(request.getParameter("price")); System.out.println("price = " + price); products.add(new Product(name, price)); } catch (NumberFormatException e) { System.err.println(e); errors.add("Price must be a number"); } context.put("errors", errors); } Template template = null; context.put("products", products); context.put("company", "Gemini Systems"); template = getTemplate("products.vm"); return template; }
Example 6
Source File: VelocityView.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Expose the tool attributes, according to corresponding bean property settings. * <p>Do not override this method unless for further tools driven by bean properties. * Override one of the {@code exposeHelpers} methods to add custom helpers. * @param velocityContext Velocity context that will be passed to the template * @param request current HTTP request * @throws Exception if there's a fatal error while we're adding model attributes * @see #setDateToolAttribute * @see #setNumberToolAttribute * @see #exposeHelpers(Map, HttpServletRequest) * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse) */ protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception { // Expose generic attributes. if (this.toolAttributes != null) { for (Map.Entry<String, Class<?>> entry : this.toolAttributes.entrySet()) { String attributeName = entry.getKey(); Class<?> toolClass = entry.getValue(); try { Object tool = toolClass.newInstance(); initTool(tool, velocityContext); velocityContext.put(attributeName, tool); } catch (Exception ex) { throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex); } } } // Expose locale-aware DateTool/NumberTool attributes. if (this.dateToolAttribute != null || this.numberToolAttribute != null) { if (this.dateToolAttribute != null) { velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(request)); } if (this.numberToolAttribute != null) { velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(request)); } } }
Example 7
Source File: BaseContentRenderer.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
@Override public String render(Content content, long modelId, String langCode, RequestContext reqCtx) { String renderedEntity = null; List<TextAttributeCharReplaceInfo> conversions = null; try { conversions = this.convertSpecialCharacters(content, langCode); String contentModel = this.getModelShape(modelId); Context velocityContext = new VelocityContext(); ContentWrapper contentWrapper = (ContentWrapper) this.getEntityWrapper(content); contentWrapper.setRenderingLang(langCode); contentWrapper.setReqCtx(reqCtx); velocityContext.put(this.getEntityWrapperContextName(), contentWrapper); I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager()); velocityContext.put("i18n", i18nWrapper); SystemInfoWrapper systemInfoWrapper = new SystemInfoWrapper(reqCtx); velocityContext.put("info", systemInfoWrapper); StringWriter stringWriter = new StringWriter(); boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", contentModel); if (!isEvaluated) { throw new ApsSystemException("Error rendering content"); } stringWriter.flush(); renderedEntity = stringWriter.toString(); } catch (Throwable t) { _logger.error("Error rendering content", t); //ApsSystemUtils.logThrowable(t, this, "render", "Error rendering content"); renderedEntity = ""; } finally { if (null != conversions) { this.replaceSpecialCharacters(conversions); } } return renderedEntity; }
Example 8
Source File: ExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Note - this is the one case where RuntimeExceptions *are not* passed through * verbatim. * @throws Exception */ public void testMethodExceptionEventHandlerException() throws Exception { ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.EVENTHANDLER_METHODEXCEPTION,ExceptionGeneratingEventHandler.class.getName()); ve.init(); Context context = new VelocityContext(); context.put ("test",new TestProvider()); assertMethodInvocationException(ve,context,"$test.getThrow()"); assertMethodInvocationException(ve,context,"$test.throw"); }
Example 9
Source File: CourseCreationConfiguration.java From olat with Apache License 2.0 | 5 votes |
/** * @param translator * @return single page content */ public String getSinglePageText(final Translator translator) { final VelocityContainer vc = new VelocityContainer("singlePageTemplate", CourseCreationHelper.class, "singlePageTemplate", translator, null); vc.contextPut("coursetitle", courseTitle); // prepare rendering of velocity page for the content of the single page node final GlobalSettings globalSettings = new GlobalSettings() { @Override public int getFontSize() { return 100; } @Override public AJAXFlags getAjaxFlags() { return new EmptyAJAXFlags(); } @Override public ComponentRenderer getComponentRendererFor(final Component source) { return null; } @Override public boolean isIdDivsForced() { return false; } }; final Context context = vc.getContext(); final Renderer fr = Renderer.getInstance(vc, translator, null, new RenderResult(), globalSettings); final VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc); context.put("r", vrdec); final VelocityHelper vh = (VelocityHelper) CoreSpringFactory.getBean(VelocityHelper.class); final String bodyMarkup = vh.mergeContent(vc.getPage(), context, null); return HTMLEditor_EBL.createXHtmlFileContent(bodyMarkup, courseTitle); }
Example 10
Source File: VelocityWrapper.java From GeoTriples with Apache License 2.0 | 5 votes |
private static Context initDefaultContext(D2RServer server) { Context context = new VelocityContext(); context.put("truncated_results", new Boolean(server.hasTruncatedResults())); context.put("server_name", server.serverName()); context.put("home_link", server.baseURI()); return context; }
Example 11
Source File: VelocityLayoutServlet.java From velocity-tools with Apache License 2.0 | 5 votes |
/** * Overrides VelocityViewServlet to check the request for * an alternate layout * * @param ctx context for this request * @param request client request */ protected void fillContext(Context ctx, HttpServletRequest request) { String layout = findLayout(request); if (layout != null) { // let the template know what its new layout is ctx.put(KEY_LAYOUT, layout); } }
Example 12
Source File: GoVelocityView.java From gocd with Apache License 2.0 | 4 votes |
private void setPrincipal(Context velocityContext, AuthenticationToken<?> authentication) { velocityContext.put(PRINCIPAL, authentication.getUser().getDisplayName()); }
Example 13
Source File: GoVelocityView.java From gocd with Apache License 2.0 | 4 votes |
private void setAnonymousUser(Context velocityContext, AuthenticationToken<?> authentication) { velocityContext.put(IS_ANONYMOUS_USER, "anonymous".equalsIgnoreCase(authentication.getUser().getDisplayName())); }
Example 14
Source File: SakaiIFrame.java From sakai with Educational Community License v2.0 | 4 votes |
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = getTitleString(request); if ( title != null ) response.setTitle(title); Context context = new VelocityContext(); context.put("tlang", rb); context.put("validator", formattedText); sendAlert(request,context); PortletURL url = response.createActionURL(); context.put("actionUrl", url.toString()); context.put("doCancel", "sakai.cancel"); context.put("doUpdate", "sakai.update"); // get current site Placement placement = ToolManager.getCurrentPlacement(); String siteId = ""; // find the right LTIContent object for this page String source = placement.getPlacementConfig().getProperty(SOURCE); Long key = getContentIdFromSource(source); if ( key == null ) { out.println(rb.getString("get.info.notconfig")); log.warn("Cannot find content id placement={} source={}", placement.getId(), source); return; } Map<String, Object> content = m_ltiService.getContent(key, placement.getContext()); if ( content == null ) { out.println(rb.getString("get.info.notconfig")); log.warn("Cannot find content item placement={} key={}", placement.getId(), key); return; } // attach the ltiToolId to each model attribute, so that we could have the tool configuration page for multiple tools String foundLtiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString(); Map<String, Object> tool = m_ltiService.getTool(Long.valueOf(foundLtiToolId), placement.getContext()); if ( tool == null ) { out.println(rb.getString("get.info.notconfig")); log.warn("Cannot find tool placement={} key={}", placement.getId(), foundLtiToolId); return; } String[] contentToolModel = m_ltiService.getContentModelIfConfigurable(Long.valueOf(foundLtiToolId), placement.getContext()); if (contentToolModel != null) { String formInput = m_ltiService.formInput(content, contentToolModel); context.put("formInput", formInput); } else { String noCustomizations = rb.getString("gen.info.nocustom"); context.put("noCustomizations", noCustomizations); } vHelper.doTemplate(vengine, "/vm/edit.vm", context, out); }
Example 15
Source File: PortletIFrame.java From sakai with Educational Community License v2.0 | 4 votes |
private void sendAlert(RenderRequest request, Context context) { PortletSession pSession = request.getPortletSession(true); String str = (String) pSession.getAttribute(ALERT_MESSAGE); pSession.removeAttribute(ALERT_MESSAGE); if ( str != null && str.length() > 0 ) context.put("alertMessage", formattedText.escapeHtml(str, false)); }
Example 16
Source File: Test6.java From java-course-ee with MIT License | 4 votes |
public Test6() throws Exception { Velocity.init("src/main/java/velocity.properties"); Template template = Velocity.getTemplate("Test6.vm"); Context context = new VelocityContext(); Collection products = new ArrayList(); products.add(new Product("Widget", 12.99)); products.add(new Product("Wotsit", 13.99)); products.add(new Product("Thingy", 11.99)); context.put("products", products); // Writer writer = new StringWriter(); // template.merge(context, writer); // System.out.println(writer.toString()); Template template2 = Velocity.getTemplate("Test7.vm"); Writer writer2 = new StringWriter(); template2.merge(context, writer2); System.out.println(writer2.toString()); }
Example 17
Source File: MetricsDisplayer.java From ApprovalTests.Java with Apache License 2.0 | 4 votes |
public void setupContext(Context context) { context.put("stats", stats); }
Example 18
Source File: TemplateError.java From ApprovalTests.Java with Apache License 2.0 | 4 votes |
public void setupContext(Context context) { context.put("error", this); }
Example 19
Source File: VelocityLayoutServlet.java From velocity-tools with Apache License 2.0 | 4 votes |
/** * Overrides VelocityViewServlet to display user's custom error template * @param request servlet request * @param response servlet response * @param e thrown error */ protected void error(HttpServletRequest request, HttpServletResponse response, Throwable e) { try { // get a velocity context Context ctx = createContext(request, response); Throwable cause = e; // if it's an MIE, i want the real cause and stack trace! if (cause instanceof MethodInvocationException) { // put the invocation exception in the context ctx.put(KEY_ERROR_INVOCATION_EXCEPTION, e); // get the real cause cause = cause.getCause(); } // add the cause to the context ctx.put(KEY_ERROR_CAUSE, cause); // grab the cause's stack trace and put it in the context StringWriter sw = new StringWriter(); cause.printStackTrace(new java.io.PrintWriter(sw)); ctx.put(KEY_ERROR_STACKTRACE, sw.toString()); // retrieve and render the error template Template et = getTemplate(errorTemplate); mergeTemplate(et, ctx, response); } catch (Exception e2) { // d'oh! log this getLog().error("Error during error template rendering", e2); // then punt the original to a higher authority super.error(request, response, e); } }
Example 20
Source File: EmailSenderImp.java From swellrt with Apache License 2.0 | 3 votes |
@Override public String getTemplateMessage(Template template, String messageBundleName, Map<String, Object> params, Locale locale) { Map<String, Object> ctx = new HashMap<String, Object>(); if (locale == null) { locale = Locale.getDefault(); } ctx.put("locale", locale); ctx.put(ResourceTool.BUNDLES_KEY, getDecoupledBundleName(messageBundleName)); ctx.put(CustomResourceTool.CLASS_LOADER_KEY, propertyClassloader); Context context = manager.createContext(ctx); Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator(); while (it.hasNext()) { Entry<String, Object> p = it.next(); context.put(p.getKey(), p.getValue()); } context.put("esc", new EscapeTool()); StringWriter sw = new StringWriter(); template.merge(context, sw); sw.flush(); return sw.toString(); }