org.apache.velocity.tools.generic.DateTool Java Examples

The following examples show how to use org.apache.velocity.tools.generic.DateTool. 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: VelocityUtils.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
public static VelocityContext createContext(DeviceMetaData deviceMetaData, FromDeviceMsg payload) {
  VelocityContext context = new VelocityContext();
  context.put("date", new DateTool());
  context.put("math", new org.apache.velocity.tools.generic.MathTool());

  DeviceAttributes deviceAttributes = deviceMetaData.getDeviceAttributes();

  pushAttributes(context, deviceAttributes.getClientSideAttributes(), NashornJsEvaluator.CLIENT_SIDE);
  pushAttributes(context, deviceAttributes.getServerSideAttributes(), NashornJsEvaluator.SERVER_SIDE);
  pushAttributes(context, deviceAttributes.getServerSidePublicAttributes(), NashornJsEvaluator.SHARED);

  switch (payload.getMsgType()) {
  case POST_TELEMETRY_REQUEST:
    pushTsEntries(context, (TelemetryUploadRequest) payload);
    break;
  }

  context.put("deviceId", deviceMetaData.getDeviceId().getId().toString());
  context.put("deviceName", deviceMetaData.getDeviceName());
  context.put("deviceType", deviceMetaData.getDeviceType());

  return context;
}
 
Example #2
Source File: GenericToolsTests.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
public @Test void testDateTool() { /* TODO still incomplete */
    DateTool dateTool = (DateTool)toolbox.get("date");
    assertNotNull(dateTool);
    Date date = new GregorianCalendar(2007,0,2).getTime();
    String disp = "2007-01-02";
    String disp2 = "2007/01/02";
    /* check configured format */
    assertEquals("yyyy-MM-dd",dateTool.getFormat());
    /* test formatting */
    assertEquals(disp,dateTool.format(date));
    assertEquals(disp2,dateTool.format("yyyy/MM/dd",date));
    /* test parsing */
    assertEquals(new Integer(2007),dateTool.getYear(disp));
    assertEquals(new Integer(0),dateTool.getMonth(disp));
    assertEquals(new Integer(2),dateTool.getDay(disp));
}
 
Example #3
Source File: VelocityBuilder.java    From feeyo-hlsserver with Apache License 2.0 5 votes vote down vote up
private void mergeTemplate(String name, String encoding, Map<String, Object> model, StringWriter writer) 
		throws ResourceNotFoundException, ParseErrorException, Exception {
	
    VelocityContext velocityContext = new VelocityContext(model);
    velocityContext.put("dateSymbol", new DateTool());
    velocityContext.put("numberSymbol", new NumberTool());
    velocityContext.put("mathSymbol", new MathTool());

    Template template = engine().getTemplate(name, encoding);
    template.merge(velocityContext, writer);
}
 
Example #4
Source File: SpringMailService.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: VelocityTemplateEngine.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #6
Source File: VelocityViewTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@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());
}
 
Example #7
Source File: VelocityToolboxViewTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testVelocityToolboxView() throws Exception {
	final String templateName = "test.vm";

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	final Template expectedTemplate = new Template();
	VelocityConfig vc = new VelocityConfig() {
		@Override
		public VelocityEngine getVelocityEngine() {
			return new TestVelocityEngine(templateName, expectedTemplate);
		}
	};
	wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc);

	final HttpServletRequest expectedRequest = new MockHttpServletRequest();
	final HttpServletResponse expectedResponse = new MockHttpServletResponse();

	VelocityToolboxView vv = new VelocityToolboxView() {
		@Override
		protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
			assertTrue(template == expectedTemplate);
			assertTrue(response == expectedResponse);
			assertTrue(context instanceof ChainedContext);

			assertEquals("this is foo.", context.get("foo"));
			assertTrue(context.get("map") instanceof HashMap<?,?>);
			assertTrue(context.get("date") instanceof DateTool);
			assertTrue(context.get("math") instanceof MathTool);

			assertTrue(context.get("link") instanceof LinkTool);
			LinkTool linkTool = (LinkTool) context.get("link");
			assertNotNull(linkTool.getContextURL());

			assertTrue(context.get("link2") instanceof LinkTool);
			LinkTool linkTool2 = (LinkTool) context.get("link2");
			assertNotNull(linkTool2.getContextURL());
		}
	};

	vv.setUrl(templateName);
	vv.setApplicationContext(wac);
	Map<String, Class<?>> toolAttributes = new HashMap<String, Class<?>>();
	toolAttributes.put("math", MathTool.class);
	toolAttributes.put("link2", LinkTool.class);
	vv.setToolAttributes(toolAttributes);
	vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml");
	vv.setExposeSpringMacroHelpers(false);

	vv.render(new HashMap<String,Object>(), expectedRequest, expectedResponse);
}