• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package de.timroes.axmlrpc.serializer;
2 
3 import java.text.SimpleDateFormat;
4 
5 import org.w3c.dom.Element;
6 
7 import de.timroes.axmlrpc.XMLRPCException;
8 import de.timroes.axmlrpc.XMLUtil;
9 import de.timroes.axmlrpc.xmlcreator.XmlElement;
10 import fr.turri.jiso8601.Iso8601Deserializer;
11 
12 /**
13  *
14  * @author timroes
15  */
16 public class DateTimeSerializer implements Serializer {
17 
18 	public static final String DEFAULT_DATETIME_FORMAT = "yyyyMMdd'T'HHmmss";
19 	private final SimpleDateFormat dateFormatter;
20 
21 	private final boolean accepts_null_input;
22 
DateTimeSerializer(boolean accepts_null_input)23 	public DateTimeSerializer(boolean accepts_null_input) {
24 		this.accepts_null_input = accepts_null_input;
25 		this.dateFormatter = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
26 	}
27 
DateTimeSerializer(boolean accepts_null_input, String datetimeFormat)28 	public DateTimeSerializer(boolean accepts_null_input, String datetimeFormat) {
29 		this.accepts_null_input = accepts_null_input;
30 		this.dateFormatter = new SimpleDateFormat(datetimeFormat);
31 	}
32 
33 
34 	@Override
deserialize(Element content)35 	public Object deserialize(Element content) throws XMLRPCException {
36 		return deserialize(XMLUtil.getOnlyTextContent(content.getChildNodes()));
37 	}
38 
deserialize(String dateStr)39 	public Object deserialize(String dateStr) throws XMLRPCException {
40 		if (accepts_null_input && (dateStr==null || dateStr.trim().length()==0)) {
41 			return null;
42 		}
43 
44 		try {
45 			return Iso8601Deserializer.toDate(dateStr);
46 		} catch (Exception ex) {
47 			throw new XMLRPCException("Unable to parse given date.", ex);
48 		}
49 	}
50 
51 	@Override
serialize(Object object)52 	public XmlElement serialize(Object object) {
53 		return XMLUtil.makeXmlTag(SerializerHandler.TYPE_DATETIME,
54 				dateFormatter.format(object));
55 	}
56 
57 }
58