KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > extended > GregorianCalendarConverter


1 package com.thoughtworks.xstream.converters.extended;
2
3 import com.thoughtworks.xstream.converters.Converter;
4 import com.thoughtworks.xstream.converters.MarshallingContext;
5 import com.thoughtworks.xstream.converters.UnmarshallingContext;
6 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
7 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
8 import com.thoughtworks.xstream.core.JVM;
9
10 import java.util.GregorianCalendar JavaDoc;
11 import java.util.Date JavaDoc;
12
13 /**
14  * Converts a java.util.GregorianCalendar to XML. Note that although it currently only contains one field, it nests
15  * it inside a child element, to allow for other fields to be stored in the future.
16  *
17  * @author Joe Walnes
18  */

19 public class GregorianCalendarConverter implements Converter {
20
21     public boolean canConvert(Class JavaDoc type) {
22         return type.equals(GregorianCalendar JavaDoc.class);
23     }
24
25     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
26         GregorianCalendar JavaDoc calendar = (GregorianCalendar JavaDoc) source;
27         writer.startNode("time");
28         long timeInMillis = calendar.getTime().getTime(); // calendar.getTimeInMillis() not available under JDK 1.3
29
writer.setValue(String.valueOf(timeInMillis));
30         writer.endNode();
31     }
32
33     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
34         reader.moveDown();
35         long timeInMillis = Long.parseLong(reader.getValue());
36         reader.moveUp();
37
38         GregorianCalendar JavaDoc result = new GregorianCalendar JavaDoc();
39         result.setTime(new Date JavaDoc(timeInMillis)); // calendar.setTimeInMillis() not available under JDK 1.3
40

41         return result;
42     }
43
44 }
45
Popular Tags