KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > collections > TreeSetConverter


1 package com.thoughtworks.xstream.converters.collections;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.converters.ConversionException;
5 import com.thoughtworks.xstream.converters.MarshallingContext;
6 import com.thoughtworks.xstream.converters.UnmarshallingContext;
7 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
9
10 import java.util.Comparator JavaDoc;
11 import java.util.TreeSet JavaDoc;
12
13 /**
14  * Converts a java.util.TreeSet to XML, and serializes
15  * the associated java.util.Comparator.
16  *
17  * @author Joe Walnes
18  */

19 public class TreeSetConverter extends CollectionConverter {
20
21     public TreeSetConverter(ClassMapper classMapper, String JavaDoc classAttributeIdentifier) {
22         super(classMapper, classAttributeIdentifier);
23     }
24
25     public boolean canConvert(Class JavaDoc type) {
26         return type.equals(TreeSet JavaDoc.class);
27     }
28
29     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
30         TreeSet JavaDoc treeSet = (TreeSet JavaDoc) source;
31         Comparator JavaDoc comparator = treeSet.comparator();
32         if (comparator == null) {
33             writer.startNode("no-comparator");
34             writer.endNode();
35         } else {
36             writer.startNode("comparator");
37             writer.addAttribute("class", classMapper.lookupName(comparator.getClass()));
38             context.convertAnother(comparator);
39             writer.endNode();
40         }
41         super.marshal(source, writer, context);
42     }
43
44     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
45         reader.moveDown();
46         TreeSet JavaDoc result;
47         if (reader.getNodeName().equals("comparator")) {
48             String JavaDoc comparatorClass = reader.getAttribute("class");
49             Comparator JavaDoc comparator = (Comparator JavaDoc) context.convertAnother(null, classMapper.lookupType(comparatorClass));
50             result = new TreeSet JavaDoc(comparator);
51         } else if (reader.getNodeName().equals("no-comparator")) {
52             result = new TreeSet JavaDoc();
53         } else {
54             throw new ConversionException("TreeSet does not contain <comparator> element");
55         }
56         reader.moveUp();
57         super.populateCollection(reader, context, result);
58         return result;
59     }
60
61 }
62
Popular Tags