KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > dozer > util > mapping > converters > CalendarConverter


1 /*
2  * Copyright 2005-2007 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of 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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16  package net.sf.dozer.util.mapping.converters;
17
18 import java.text.DateFormat JavaDoc;
19 import java.text.ParseException JavaDoc;
20 import java.util.Calendar JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.GregorianCalendar JavaDoc;
23
24 import org.apache.commons.beanutils.Converter;
25
26 /**
27  * @author tierney.matt
28  */

29 public class CalendarConverter implements Converter {
30
31   private DateFormat JavaDoc dateFormat;
32
33   public CalendarConverter(DateFormat JavaDoc dateFormat) {
34     this.dateFormat = dateFormat;
35   }
36
37   public Object JavaDoc convert(Class JavaDoc destClass, Object JavaDoc sourceObj) {
38     Calendar JavaDoc result = new GregorianCalendar JavaDoc();
39     Class JavaDoc sourceFieldClass = sourceObj.getClass();
40     //Convert from Date to Calendar
41
if (java.util.Date JavaDoc.class.isAssignableFrom(sourceFieldClass)) {
42       result.setTime( (java.util.Date JavaDoc) sourceObj);
43     }
44     //Convert from Calendar to Calendar
45
else if (Calendar JavaDoc.class.isAssignableFrom(sourceFieldClass)) {
46       Calendar JavaDoc c = (Calendar JavaDoc) sourceObj;
47       result.setTime(c.getTime());
48     }
49     //String to Calendar
50
else if (dateFormat != null && String JavaDoc.class.isAssignableFrom(sourceFieldClass)) {
51       try {
52         result.setTime(new Date JavaDoc(dateFormat.parse( (String JavaDoc) sourceObj).getTime()));
53       } catch (ParseException JavaDoc e) {
54         throw new ConversionException("Unable to parse source object using specified date format", e);
55       }
56     //Default conversion
57
} else {
58         try {
59           result.setTime(new Date JavaDoc(Long.parseLong(sourceObj.toString())));
60         }
61         catch (NumberFormatException JavaDoc e) {
62           throw new ConversionException("Unable to determine time in millis of source object", e);
63         }
64     }
65     return result;
66   }
67
68   public DateFormat JavaDoc getDateFormat() {
69     return dateFormat;
70   }
71
72   public void setDateFormat(DateFormat JavaDoc dateFormat) {
73     this.dateFormat = dateFormat;
74   }
75 }
76
Popular Tags