01: package org.geotools.xml;
02:
03: import java.sql.Time;
04: import java.sql.Timestamp;
05: import java.util.Calendar;
06: import java.util.Date;
07:
08: import javax.xml.bind.DatatypeConverter;
09:
10: import org.apache.commons.beanutils.converters.SqlDateConverter;
11: import org.geotools.factory.Hints;
12: import org.geotools.util.CommonsConverterFactory;
13: import org.geotools.util.Converter;
14: import org.geotools.util.ConverterFactory;
15:
16: import com.sun.xml.bind.DatatypeConverterImpl;
17:
18: /**
19: * A ConverterFactory which can convert strings using {@link javax.xml.datatype.DatatypeFactory}.
20: * <p>
21: * Supported converstions:
22: * <ul>
23: * <li>String to {@link java.util.Date}
24: * <li>String to {@link java.util.Calendar}
25: * </ul>
26: * </p>
27: *
28: * @author Justin Deoliveira, The Open Planning Project
29: *
30: */
31: public class XmlConverterFactory implements ConverterFactory {
32:
33: static {
34: DatatypeConverter
35: .setDatatypeConverter(DatatypeConverterImpl.theInstance);
36: }
37:
38: public Converter createConverter(Class source, Class target,
39: Hints hints) {
40: if (String.class.equals(source)) {
41: return new XmlConverter();
42: }
43:
44: return null;
45: }
46:
47: static class XmlConverter implements Converter {
48:
49: public Object convert(Object source, Class target)
50: throws Exception {
51: String value = (String) source;
52:
53: //JD: this is a bit of a hack but delegate to the
54: // commons converter in case we are executing first.
55: Converter converter = new CommonsConverterFactory()
56: .createConverter(value.getClass(), target, null);
57: if (converter != null) {
58: Object converted = converter.convert(source, target);
59: if (converted != null) {
60: return converted;
61: }
62: }
63:
64: Calendar date;
65: //try parsing as dateTime
66: try {
67: date = DatatypeConverter.parseDateTime(value);
68: } catch (Exception e) {
69: //try as just date
70: date = DatatypeConverter.parseDate(value);
71: }
72:
73: if (Calendar.class.equals(target)) {
74: return date;
75: }
76:
77: if (Date.class.isAssignableFrom(target)) {
78: Date time = date.getTime();
79:
80: //check for subclasses
81: if (java.sql.Date.class.equals(target)) {
82: return new java.sql.Date(time.getTime());
83: }
84: if (Time.class.equals(target)) {
85: return new Time(time.getTime());
86: }
87: if (Timestamp.class.equals(target)) {
88: return new Timestamp(time.getTime());
89: }
90:
91: return time;
92: }
93:
94: return null;
95: }
96:
97: }
98:
99: }
|