1 package com.panogenesis.util;
2
3 import java.text.DateFormat;
4 import java.text.SimpleDateFormat;
5
6 import java.util.Date;
7
8 import org.apache.commons.beanutils.ConversionException;
9 import org.apache.commons.beanutils.Converter;
10 import org.apache.commons.lang.StringUtils;
11
12
13 /***
14 * This class is converts a java.util.Date to a String
15 * and a String to a java.util.Date. It is used by
16 * BeanUtils when copying properties. Registered
17 * for use in BaseAction.
18 *
19 * <p>
20 * <a href="DateConverter.java.html"><i>View Source</i></a>
21 * </p>
22 *
23 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
24 */
25 public class DateConverter implements Converter {
26 private static DateFormat df =
27 new SimpleDateFormat(DateUtil.getDatePattern());
28
29 public Object convert(Class type, Object value) {
30 if (value == null) {
31 return null;
32 } else if (type == Date.class) {
33 return convertToDate(type, value);
34 } else if (type == String.class) {
35 return convertToString(type, value);
36 }
37
38 throw new ConversionException("Could not convert " +
39 value.getClass().getName() + " to " +
40 type.getName());
41 }
42
43 protected Object convertToDate(Class type, Object value) {
44 if (value instanceof String) {
45 try {
46 if (StringUtils.isEmpty(value.toString())) {
47 return null;
48 }
49
50 return df.parse((String) value);
51 } catch (Exception pe) {
52 throw new ConversionException("Error converting String to Date");
53 }
54 }
55
56 throw new ConversionException("Could not convert " +
57 value.getClass().getName() + " to " +
58 type.getName());
59 }
60
61 protected Object convertToString(Class type, Object value) {
62 if (value instanceof Date) {
63 try {
64 return df.format(value);
65 } catch (Exception e) {
66 throw new ConversionException("Error converting Date to String");
67 }
68 }
69
70 return value.toString();
71 }
72 }