01: /*
02: * Copyright (C) 2003, 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 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 01. October 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.collections;
13:
14: import com.thoughtworks.xstream.converters.MarshallingContext;
15: import com.thoughtworks.xstream.converters.UnmarshallingContext;
16: import com.thoughtworks.xstream.core.JVM;
17: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
18: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
19: import com.thoughtworks.xstream.mapper.Mapper;
20:
21: import java.util.ArrayList;
22: import java.util.Collection;
23: import java.util.HashSet;
24: import java.util.Iterator;
25: import java.util.LinkedList;
26: import java.util.Vector;
27:
28: /**
29: * Converts most common Collections (Lists and Sets) to XML, specifying a nested
30: * element for each item.
31: * <p/>
32: * <p>Supports java.util.ArrayList, java.util.HashSet,
33: * java.util.LinkedList, java.util.Vector and java.util.LinkedHashSet.</p>
34: *
35: * @author Joe Walnes
36: */
37: public class CollectionConverter extends AbstractCollectionConverter {
38:
39: public CollectionConverter(Mapper mapper) {
40: super (mapper);
41: }
42:
43: public boolean canConvert(Class type) {
44: return type.equals(ArrayList.class)
45: || type.equals(HashSet.class)
46: || type.equals(LinkedList.class)
47: || type.equals(Vector.class)
48: || (JVM.is14() && type.getName().equals(
49: "java.util.LinkedHashSet"));
50: }
51:
52: public void marshal(Object source, HierarchicalStreamWriter writer,
53: MarshallingContext context) {
54: Collection collection = (Collection) source;
55: for (Iterator iterator = collection.iterator(); iterator
56: .hasNext();) {
57: Object item = iterator.next();
58: writeItem(item, context, writer);
59: }
60: }
61:
62: public Object unmarshal(HierarchicalStreamReader reader,
63: UnmarshallingContext context) {
64: Collection collection = (Collection) createCollection(context
65: .getRequiredType());
66: populateCollection(reader, context, collection);
67: return collection;
68: }
69:
70: protected void populateCollection(HierarchicalStreamReader reader,
71: UnmarshallingContext context, Collection collection) {
72: while (reader.hasMoreChildren()) {
73: reader.moveDown();
74: Object item = readItem(reader, context, collection);
75: collection.add(item);
76: reader.moveUp();
77: }
78: }
79:
80: }
|