LocaleBasedCalendarConverter implements Converter<Calendar> { public Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle) { if (isNullOrEmpty(value)) { return null; } Locale locale = localization.getLocale(); if (locale == null) { locale = Locale.getDefault(); } DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, locale); try { Date date = format.parse(value); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); return calendar; } catch (ParseException e) { throw new ConversionError(MessageFormat.format(bundle.getString("is_not_a_valid_date"), value)); } } LocaleBasedCalendarConverter(Localization localization); Calendar convert(String value, Class<? extends Calendar> type, ResourceBundle bundle);  }
@Test public void shouldBeAbleToConvert() { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn("pt_br"); assertThat(converter.convert("10/06/2008", Calendar.class, bundle), is(equalTo((Calendar) new GregorianCalendar(2008, 5, 10)))); }
@Test public void shouldUseTheDefaultLocale() throws ParseException { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn(null); when(request.getSession()).thenReturn(session); when(session.getAttribute(LOCALE_KEY + ".session")). thenReturn(null); when(context.getAttribute(LOCALE_KEY + ".application")). thenReturn(null); when(context.getInitParameter(LOCALE_KEY)). thenReturn(null); when(request.getLocale()).thenReturn(null); Date date = new SimpleDateFormat("dd/MM/yyyy").parse("10/05/2010"); Calendar cal = new GregorianCalendar(); cal.setTime(date); String formattedToday = DateFormat.getDateInstance(DateFormat.SHORT).format(date); assertThat(converter.convert(formattedToday, Calendar.class, bundle), is(equalTo(cal))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Calendar.class, bundle), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Calendar.class, bundle), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { when(request.getAttribute(LOCALE_KEY + ".request")).thenReturn("pt_br"); try { converter.convert("a,10/06/2008/a/b/c", Calendar.class, bundle); } catch (ConversionError e) { assertThat(e.getMessage(), is(equalTo("a,10/06/2008/a/b/c is not a valid date."))); } }