/** * @return a new context with some tools initialized. * * @see NumberTool * @see DateTool * @see MathTool */ public static VelocityContext getPrepopulatedVelocityContext() { final NumberTool numberTool = new NumberTool(); final DateTool dateTool = new DateTool(); final MathTool mathTool = new MathTool(); VelocityContext context = new VelocityContext(); context.put("numberTool", numberTool); context.put("dateTool", dateTool); context.put("mathTool", mathTool); context.put("enLocale", Locale.ENGLISH); context.put("service", new ICommonService() { @Override public String getHttpBaseRef() { return BLLManager.getInstance().getConfigManager().getMotuConfig().getHttpBaseRef(); } }); return context; }
/** * Generates the mail message based on the file import status. * * @param importStatus The import status to generate file import mail message. * @return The file import mail message for the status. */ private String makeImportMailMessage(ImportStatus importStatus) { Map<String, Object> model = new HashMap<String, Object>(); model.put("importStatus", importStatus); model.put("dateTool", new DateTool()); model.put("mathTool", new MathTool()); model.put("numberTool", new NumberTool()); model.put("StringUtils", StringUtils.class); try { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, fileImportMailTemplate, "utf-8", model); } catch (VelocityException ve) { logger.error("Error while making file import mail message", ve); // Use the log text instead... return logImportStatus(importStatus); } }
public static org.jxls.common.Context initializeContext(long userId) { org.jxls.common.Context jxlsContext = PoiTransformer.createInitialContext(); jxlsContext.putVar("distanceUnit", getDistanceUnit(userId)); jxlsContext.putVar("speedUnit", getSpeedUnit(userId)); jxlsContext.putVar("volumeUnit", getVolumeUnit(userId)); jxlsContext.putVar("webUrl", Context.getVelocityEngine().getProperty("web.url")); jxlsContext.putVar("dateTool", new DateTool()); jxlsContext.putVar("numberTool", new NumberTool()); jxlsContext.putVar("timezone", getTimezone(userId)); jxlsContext.putVar("locale", Locale.getDefault()); jxlsContext.putVar("bracketsRegex", "[\\{\\}\"]"); return jxlsContext; }
public static VelocityContext prepareContext(long userId, Event event, Position position) { User user = Context.getPermissionsManager().getUser(userId); Device device = Context.getIdentityManager().getById(event.getDeviceId()); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("user", user); velocityContext.put("device", device); velocityContext.put("event", event); if (position != null) { velocityContext.put("position", position); velocityContext.put("speedUnit", ReportUtils.getSpeedUnit(userId)); velocityContext.put("distanceUnit", ReportUtils.getDistanceUnit(userId)); velocityContext.put("volumeUnit", ReportUtils.getVolumeUnit(userId)); } if (event.getGeofenceId() != 0) { velocityContext.put("geofence", Context.getGeofenceManager().getById(event.getGeofenceId())); } String driverUniqueId = event.getString(Position.KEY_DRIVER_UNIQUE_ID); if (driverUniqueId != null) { velocityContext.put("driver", Context.getDriversManager().getDriverByUniqueId(driverUniqueId)); } velocityContext.put("webUrl", Context.getVelocityEngine().getProperty("web.url")); velocityContext.put("dateTool", new DateTool()); velocityContext.put("numberTool", new NumberTool()); velocityContext.put("timezone", ReportUtils.getTimezone(userId)); velocityContext.put("locale", Locale.getDefault()); return velocityContext; }
private void generateHtmlfile(Map<String, Object> input) { try{ VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName()); ve.init(); Template template = ve.getTemplate("templates/acmeair-report.vtl"); VelocityContext context = new VelocityContext(); for(Map.Entry<String, Object> entry: input.entrySet()){ context.put(entry.getKey(), entry.getValue()); } context.put("math", new MathTool()); context.put("number", new NumberTool()); context.put("date", new ComparisonDateTool()); Writer file = new FileWriter(new File(searchingLocation + System.getProperty("file.separator") + RESULTS_FILE)); template.merge( context, file ); file.flush(); file.close(); }catch(Exception e){ e.printStackTrace(); } }
/** * Velocity 模板发送邮件 html 格式 * * @param to * @param subject * @throws javax.mail.MessagingException */ public void sendMailVelocity(String from ,String[] to, String subject) throws MessagingException { //如果不是 html 格式,修改为 SimpleMailMessage MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.toString()); /** *邮件内容 */ helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); //模板内容 Map<String, Object> model = new HashMap<String, Object>(); model.put("firstName", "Yashwant"); model.put("lastName", "Chavan"); model.put("location", "china"); //创建动态 bean DynaBean dynaBean = new LazyDynaBean(); dynaBean.set("name", "It is name"); //simple dynaBean.set("gender", new Integer(1)); //simple //设置 bean 属性 // Velocity 工具类,实例可以直接放入 map ,在模板文件中直接使用 // 如日期格式化 $dateTool.format("yyyy-MM-dd",$info.issueTime) DateTool dateTool = new DateTool();//日期工具 NumberTool numberTool = new NumberTool();//数字工具 model.put("dateTool",dateTool); model.put("numberTool",numberTool); model.put("bean", dynaBean); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "./templates/velocity_template_email-newsletter.vm", StandardCharsets.UTF_8.toString(), model); helper.setText(text, true); mailSender.send(message); }
/** * Initializes Velocity engine */ private void init() { velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "class"); velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); setLogFile(); DateTool dateTool = new DateTool(); dateTool.configure(this.configMap); MathTool mathTool = new MathTool(); NumberTool numberTool = new NumberTool(); numberTool.configure(this.configMap); SortTool sortTool = new SortTool(); defaultContext = new VelocityContext(); defaultContext.put("dateTool", dateTool); defaultContext.put("dateComparisonTool", new ComparisonDateTool()); defaultContext.put("mathTool", mathTool); defaultContext.put("numberTool", numberTool); defaultContext.put("sortTool", sortTool); // Following tools need VelocityTools version 2.0+ //defaultContext.put("displayTool", new DisplayTool()); //defaultContext.put("xmlTool", new XmlTool()); try { velocityEngine.init(); } catch (Exception e) { throw new VelocityException(e); } }
/** * @return produz um contexto para velocity engine */ @Produces VelocityContext produceContext() { final VelocityContext context = new VelocityContext(); // tools para trabalhar com data e numeros context.put("date", new DateTool()); context.put("number", new NumberTool()); return context; }
public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException { String arquivoTemplate = mail.getTemplate(); VelocityEngine engine = new VelocityEngine(); engine.addProperty("resource.loader", "class"); engine.addProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); engine.init(); Template template = engine.getTemplate(arquivoTemplate); NumberTool numberTool = new NumberTool(); assert (numberTool != null); VelocityContext context = new VelocityContext(mail.getParametros()); context.put("numberTool", numberTool); context.put("locale", Locale.getDefault()); StringWriter writer = new StringWriter(); template.merge(context, writer); htmlContent = writer.toString(); }
@Test public void testExposeHelpers() throws Exception { final String templateName = "test.vm"; WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getServletContext()).willReturn(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>(); configurers.put("velocityConfigurer", vc); given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); // let it ask for locale HttpServletRequest req = mock(HttpServletRequest.class); given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null); given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver()); given(req.getLocale()).willReturn(Locale.CANADA); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityView vv = new VelocityView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertEquals("myValue", context.get("myHelper")); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("dateTool") instanceof DateTool); DateTool dateTool = (DateTool) context.get("dateTool"); assertTrue(dateTool.getLocale().equals(Locale.CANADA)); assertTrue(context.get("numberTool") instanceof NumberTool); NumberTool numberTool = (NumberTool) context.get("numberTool"); assertTrue(numberTool.getLocale().equals(Locale.CANADA)); } @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { model.put("myHelper", "myValue"); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); Map<String, Class<?>> toolAttributes = new HashMap<String, Class<?>>(); toolAttributes.put("math", MathTool.class); vv.setToolAttributes(toolAttributes); vv.setDateToolAttribute("dateTool"); vv.setNumberToolAttribute("numberTool"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String, Object>(), req, expectedResponse); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType()); }
@Test public void testExposeHelpers() throws Exception { final String templateName = "test.vm"; WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getServletContext()).willReturn(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>(); configurers.put("velocityConfigurer", vc); given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); // let it ask for locale HttpServletRequest req = mock(HttpServletRequest.class); given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null); given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver()); given(req.getLocale()).willReturn(Locale.CANADA); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); VelocityView vv = new VelocityView() { @Override protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception { assertTrue(template == expectedTemplate); assertTrue(response == expectedResponse); assertEquals("myValue", context.get("myHelper")); assertTrue(context.get("math") instanceof MathTool); assertTrue(context.get("dateTool") instanceof DateTool); DateTool dateTool = (DateTool) context.get("dateTool"); assertTrue(dateTool.getLocale().equals(Locale.CANADA)); assertTrue(context.get("numberTool") instanceof NumberTool); NumberTool numberTool = (NumberTool) context.get("numberTool"); assertTrue(numberTool.getLocale().equals(Locale.CANADA)); } @Override protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception { model.put("myHelper", "myValue"); } }; vv.setUrl(templateName); vv.setApplicationContext(wac); Map<String, Class> toolAttributes = new HashMap<String, Class>(); toolAttributes.put("math", MathTool.class); vv.setToolAttributes(toolAttributes); vv.setDateToolAttribute("dateTool"); vv.setNumberToolAttribute("numberTool"); vv.setExposeSpringMacroHelpers(false); vv.render(new HashMap<String, Object>(), req, expectedResponse); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType()); }
public void generateReport(JenkinsView viewData, PrintWriter out, Date startTime) { final List<Job> failedJobs = newArrayList(); failedJobs.addAll(viewData.getFailedJobs()); // sort jobs by build timestamp Collections.sort(failedJobs, new JobByTimestampComparator()); final List<Job> passedJobs = newArrayList(); passedJobs.addAll(viewData.getPassedJobs()); // sort jobs by build timestamp Collections.sort(passedJobs, new JobByTimestampComparator()); final VelocityContext context = new VelocityContext(); context.put("startTime", startTime); final DateTool dateTool = new DateTool(); final Map<String, String> config = new HashMap<String, String>(); config.put("timezone", "Europe/Tallinn"); dateTool.configure(config); context.put("dateTool", dateTool); final NumberTool numberTool = new NumberTool(); numberTool.configure(config); context.put("numberTool", numberTool); final EscapeTool escapeTool = new EscapeTool(); context.put("escapeTool", escapeTool); context.put("view", viewData); context.put("failedJobs", failedJobs); context.put("passedJobs", passedJobs); final StringWriter writer = new StringWriter(); template.merge(context, writer); out.println(writer.toString()); out.flush(); out.close(); }
/** * Creates a message object with a set of standard parameters * @param entityId * @param userId * @return The message object with many useful parameters */ private MessageDTO initializeMessage(Integer entityId, Integer userId) throws SessionInternalError { MessageDTO retValue = new MessageDTO(); try { UserBL user = new UserBL(userId); ContactBL contact = new ContactBL(); // this user's info contact.set(userId); if (contact.getEntity() != null) { retValue.addParameter("contact", contact.getEntity()); retValue.addParameter("first_name", contact.getEntity().getFirstName()); retValue.addParameter("last_name", contact.getEntity().getLastName()); retValue.addParameter("address1", contact.getEntity().getAddress1()); retValue.addParameter("address2", contact.getEntity().getAddress2()); retValue.addParameter("city", contact.getEntity().getCity()); retValue.addParameter("organization_name", contact.getEntity().getOrganizationName()); retValue.addParameter("postal_code", contact.getEntity().getPostalCode()); retValue.addParameter("state_province", contact.getEntity().getStateProvince()); } if (user.getEntity() != null) { retValue.addParameter("user", user.getEntity()); retValue.addParameter("username", user.getEntity().getUserName()); retValue.addParameter("password", user.getEntity().getPassword()); retValue.addParameter("user_id", user.getEntity().getUserId().toString()); } if (user.getCreditCard() != null) { retValue.addParameter("credit_card", user.getCreditCard()); } // the entity info contact.setEntity(entityId); if (contact.getEntity() != null) { retValue.addParameter("company_contact", contact.getEntity()); retValue.addParameter("company_id", entityId.toString()); retValue.addParameter("company_name", contact.getEntity().getOrganizationName()); } //velocity tools retValue.addParameter("tools-date", new DateTool()); retValue.addParameter("tools-math", new MathTool()); retValue.addParameter("tools-number", new NumberTool()); retValue.addParameter("tools-render", new RenderTool()); retValue.addParameter("tools-escape", new EscapeTool()); retValue.addParameter("tools-resource", new ResourceTool()); retValue.addParameter("tools-alternator", new AlternatorTool()); // retValue.addParameter("tools-valueParser", new ValueParser()); retValue.addParameter("tools-list", new ListTool()); retValue.addParameter("tools-sort", new SortTool()); retValue.addParameter("tools-iterator", new IteratorTool()); //Adding a CCF Field to Email Template if (user.getEntity().getCustomer() != null && user.getEntity().getCustomer().getMetaFields() != null) { for (MetaFieldValue metaFieldValue : user.getEntity().getCustomer().getMetaFields()) { retValue.addParameter(metaFieldValue.getField().getName(), metaFieldValue.getValue()); } } LOG.debug("Retvalue >>>> "+retValue.toString()); LOG.debug("Retvalue partameters >>>> "+retValue.getParameters()); } catch (Exception e) { throw new SessionInternalError(e); } return retValue; }