DateFormatter implements TemplateMethodModelEx { @Override public Object exec(List args) throws TemplateModelException { if (args.size() != 3) { throw new IllegalArgumentException("Wrong arguments"); } Object date = DeepUnwrap.unwrap((TemplateModel) args.get(0)); String pattern = (String) DeepUnwrap.unwrap((TemplateModel) args.get(1)); Locale locale = (Locale) DeepUnwrap.unwrap((TemplateModel) args.get(2)); if (date instanceof LocalDate) { date = ((LocalDate)date).toDateTimeAtStartOfDay(); } String formatted = ""; if (date instanceof DateTime) { formatted = DateTimeFormat.forPattern(pattern).withLocale(locale).print((DateTime) date); } else if (date instanceof Date) { formatted = new SimpleDateFormat(pattern, locale).format((Date) date); } else if (date != null) { throw new IllegalArgumentException("Unsupported date type: " + date.getClass()); } return formatted; }  @Override Object exec(List args);  }
@Test public void formatJavaDateInEnglish() throws TemplateModelException { List<Object> args = getJavaDateArgs(Locale.ENGLISH); DateFormatter formatter = new DateFormatter(); String result = (String) formatter.exec(args); String expected = "January"; assertEquals(expected, result); }
@Test public void formatJavaDateInFrench() throws TemplateModelException { List<Object> args = getJavaDateArgs(Locale.FRENCH); DateFormatter formatter = new DateFormatter(); String result = (String) formatter.exec(args); String expected = "janvier"; assertEquals(expected, result); }
@Test public void formatJodaDateInEnglish() throws TemplateModelException { List<Object> args = getJodaDateArgs(Locale.ENGLISH); DateFormatter formatter = new DateFormatter(); String result = (String) formatter.exec(args); String expected = "January"; assertEquals(expected, result); }
@Test public void formatJodaDateInFrench() throws TemplateModelException { List<Object> args = getJodaDateArgs(Locale.FRENCH); DateFormatter formatter = new DateFormatter(); String result = (String) formatter.exec(args); String expected = "janvier"; assertEquals(expected, result); }
@Test(expected=IllegalArgumentException.class) @SuppressWarnings("PMD.EmptyCatchBlock") public void wrongDateTypeShouldFail() throws TemplateModelException { List<Object> args = getFormatterArgs("not a date!", Locale.ENGLISH); DateFormatter formatter = new DateFormatter(); formatter.exec(args); }
@Test(expected=IllegalArgumentException.class) @SuppressWarnings("PMD.EmptyCatchBlock") public void wrongNumberOfArgumentsShouldFail() throws TemplateModelException { DateFormatter formatter = new DateFormatter(); List<Object> args = new ArrayList<Object>(); formatter.exec(args); }