1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.transform.converters;
17
18 import java.util.Calendar;
19 import java.util.Date;
20 import java.util.Locale;
21
22 import net.sf.morph.transform.DecoratedConverter;
23 import net.sf.morph.transform.TransformationException;
24 import net.sf.morph.transform.transformers.BaseTransformer;
25
26 /**
27 * Converts information from one of the basic time types to the other. The basic
28 * time types are {@link java.util.Date} and {@link java.util.Calendar}.
29 *
30 * @author Matt Sgarlata
31 * @since Jan 4, 2005
32 */
33 public class TimeConverter extends BaseTransformer implements DecoratedConverter {
34
35 private static final Class[] SOURCE_AND_DESTINATION_TYPES = { Date.class, Calendar.class };
36
37 /**
38 * {@inheritDoc}
39 */
40 protected Object convertImpl(Class destinationClass, Object source, Locale locale) throws Exception {
41 if (destinationClass.isInstance(source)) {
42 return source instanceof Date ? ((Date) source).clone() : ((Calendar) source).clone();
43 }
44 if (Date.class.isAssignableFrom(destinationClass)) {
45 return ((Calendar) source).getTime();
46 }
47 if (Calendar.class.isAssignableFrom(destinationClass)) {
48 Calendar calendar = Calendar.getInstance();
49 calendar.setTime((Date) source);
50 return calendar;
51 }
52 throw new TransformationException(destinationClass, source);
53 }
54
55 /**
56 * {@inheritDoc}
57 */
58 protected Class[] getSourceClassesImpl() throws Exception {
59 return SOURCE_AND_DESTINATION_TYPES;
60 }
61
62 /**
63 * {@inheritDoc}
64 */
65 protected Class[] getDestinationClassesImpl() throws Exception {
66 return SOURCE_AND_DESTINATION_TYPES;
67 }
68
69 /**
70 * {@inheritDoc}
71 */
72 protected boolean isWrappingRuntimeExceptions() {
73 return true;
74 }
75
76 }