01: package org.vraptor.converter;
02:
03: import java.text.DateFormat;
04: import java.text.ParseException;
05: import java.util.Calendar;
06: import java.util.Date;
07: import java.util.GregorianCalendar;
08: import java.util.Locale;
09:
10: import org.vraptor.LogicRequest;
11: import org.vraptor.i18n.JstlWrapper;
12:
13: /**
14: * Locale based calendar converter. Uses the error key invalid_time if unable to
15: * parse its information.
16: *
17: * @author Guilherme Silveira
18: */
19: public class LocaleCalendarTimeConverter implements Converter {
20:
21: private final JstlWrapper jstlWrapper = new JstlWrapper();
22:
23: public Object convert(String value, Class<?> type,
24: LogicRequest context) throws ConversionException {
25: if (value == null || value.equals("")) {
26: return null;
27: }
28: Locale locale = jstlWrapper.findLocale((LogicRequest) context);
29: if (locale == null) {
30: locale = Locale.getDefault();
31: }
32: DateFormat format = DateFormat.getTimeInstance(
33: DateFormat.SHORT, locale);
34: try {
35: Date date = format.parse(value);
36: if (Date.class.isAssignableFrom(type)) {
37: return date;
38: } else {
39: Calendar calendar = new GregorianCalendar();
40: calendar.setTime(date);
41: return calendar;
42: }
43: } catch (ParseException e) {
44: throw new ConversionException("invalid_time",
45: "Unable to parse string " + value, e);
46: }
47: }
48:
49: /**
50: * Returns the list of supported types
51: *
52: * @see org.vraptor.converter.Converter#getSupportedTypes()
53: */
54: public Class<?>[] getSupportedTypes() {
55: return new Class[] { Calendar.class, Date.class };
56: }
57:
58: }
|