1 /***
2 * Copyright (C) 2008 rweber <quietgenie@users.sourceforge.net>
3 *
4 * This file is part of CsvObjectMapper.
5 *
6 * CsvObjectMapper is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CsvObjectMapper is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with CsvObjectMapper. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 /***
21 *
22 */
23 package com.projectnine.csvmapper;
24
25 import java.text.SimpleDateFormat;
26 import java.util.GregorianCalendar;
27
28 import javax.xml.datatype.DatatypeConfigurationException;
29 import javax.xml.datatype.DatatypeFactory;
30 import javax.xml.datatype.XMLGregorianCalendar;
31
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34
35 /***
36 * Convert a String into a {@link XMLGregorianCalendar}.
37 *
38 * @author robweber
39 *
40 */
41 public class CurrentXmlGregorianCalendarFieldFormatter implements
42 CsvFieldFormatter {
43 private static final Log log = LogFactory
44 .getLog(CurrentXmlGregorianCalendarFieldFormatter.class);
45 private SimpleDateFormat dateFormatter;
46
47
48
49
50
51
52
53 /***
54 * If conversion fails due to a {@link DatatypeConfigurationException}, just
55 * return null. If conversion fails due to any other error that raises an
56 * Exception, the Exception is thrown.
57 */
58 public Object formatString(String rawPropertyValue) {
59 GregorianCalendar calendar = new GregorianCalendar();
60 Object o = null;
61 try {
62 o = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
63 } catch (DatatypeConfigurationException e) {
64 log
65 .warn(
66 "An error occurred while generating the current XMLGregorianCalendar",
67 e);
68 }
69
70 return o;
71 }
72
73 public String formatObject(Object object) {
74 XMLGregorianCalendar calendar = (XMLGregorianCalendar) object;
75 return dateFormatter.format(calendar.toGregorianCalendar().getTime());
76 }
77
78 /***
79 * @param dateFormatter
80 * the dateFormatter to set
81 */
82 public void setDateFormat(String dateFormat) {
83 dateFormatter = new SimpleDateFormat(dateFormat);
84 }
85
86 }