01: /*
02: * Copyright (C) 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007, 2008 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 24. July 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.Converter;
15: import com.thoughtworks.xstream.converters.MarshallingContext;
16: import com.thoughtworks.xstream.converters.UnmarshallingContext;
17: import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
18: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
19: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
20:
21: import java.util.Date;
22: import java.util.GregorianCalendar;
23: import java.util.TimeZone;
24:
25: /**
26: * Converts a java.util.GregorianCalendar to XML. Note that although it currently only contains one field, it nests
27: * it inside a child element, to allow for other fields to be stored in the future.
28: *
29: * @author Joe Walnes
30: * @author Jörg Schaible
31: */
32: public class GregorianCalendarConverter implements Converter {
33:
34: public boolean canConvert(Class type) {
35: return type.equals(GregorianCalendar.class);
36: }
37:
38: public void marshal(Object source, HierarchicalStreamWriter writer,
39: MarshallingContext context) {
40: GregorianCalendar calendar = (GregorianCalendar) source;
41: ExtendedHierarchicalStreamWriterHelper.startNode(writer,
42: "time", long.class);
43: long timeInMillis = calendar.getTime().getTime(); // calendar.getTimeInMillis() not available under JDK 1.3
44: writer.setValue(String.valueOf(timeInMillis));
45: writer.endNode();
46: ExtendedHierarchicalStreamWriterHelper.startNode(writer,
47: "timezone", String.class);
48: writer.setValue(calendar.getTimeZone().getID());
49: writer.endNode();
50: }
51:
52: public Object unmarshal(HierarchicalStreamReader reader,
53: UnmarshallingContext context) {
54: reader.moveDown();
55: long timeInMillis = Long.parseLong(reader.getValue());
56: reader.moveUp();
57: final String timeZone;
58: if (reader.hasMoreChildren()) {
59: reader.moveDown();
60: timeZone = reader.getValue();
61: reader.moveUp();
62: } else { // backward compatibility to XStream 1.1.2 and below
63: timeZone = TimeZone.getDefault().getID();
64: }
65:
66: GregorianCalendar result = new GregorianCalendar();
67: result.setTimeZone(TimeZone.getTimeZone(timeZone));
68: result.setTime(new Date(timeInMillis)); // calendar.setTimeInMillis() not available under JDK 1.3
69:
70: return result;
71: }
72:
73: }
|