View Javadoc

1   /*
2    * Copyright 2004-2005, 2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
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  }