KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.thoughtworks.xstream.converters.collections;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.converters.MarshallingContext;
5 import com.thoughtworks.xstream.converters.UnmarshallingContext;
6 import com.thoughtworks.xstream.core.JVM;
7 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
9
10 import java.util.*;
11
12 /**
13  * Converts most common Collections (Lists and Sets) to XML, specifying a nested
14  * element for each item.
15  * <p/>
16  * <p>Supports java.util.ArrayList, java.util.HashSet,
17  * java.util.LinkedList, java.util.Vector and java.util.LinkedHashSet.</p>
18  *
19  * @author Joe Walnes
20  */

21 public class CollectionConverter extends AbstractCollectionConverter {
22
23     public CollectionConverter(ClassMapper classMapper, String JavaDoc classAttributeIdentifier) {
24         super(classMapper, classAttributeIdentifier);
25     }
26
27     public boolean canConvert(Class JavaDoc type) {
28         return type.equals(ArrayList.class)
29                 || type.equals(HashSet.class)
30                 || type.equals(LinkedList.class)
31                 || type.equals(Vector.class)
32                 || (JVM.is14() && type.getName().equals("java.util.LinkedHashSet"));
33     }
34
35     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
36         Collection collection = (Collection) source;
37         for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
38             Object JavaDoc item = iterator.next();
39             writeItem(item, context, writer);
40         }
41     }
42
43     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
44         Collection collection = (Collection) createCollection(context.getRequiredType());
45         populateCollection(reader, context, collection);
46         return collection;
47     }
48
49     protected void populateCollection(HierarchicalStreamReader reader, UnmarshallingContext context, Collection collection) {
50         while (reader.hasMoreChildren()) {
51             reader.moveDown();
52             Object JavaDoc item = readItem(reader, context, collection);
53             collection.add(item);
54             reader.moveUp();
55         }
56     }
57
58 }
59
Popular Tags