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.Converter;
|
6
|
|
import com.thoughtworks.xstream.converters.ConverterLookup;
|
7
|
|
import com.thoughtworks.xstream.objecttree.ObjectTree;
|
8
|
|
import com.thoughtworks.xstream.xml.XMLReader;
|
9
|
|
import com.thoughtworks.xstream.xml.XMLWriter;
|
10
|
|
|
11
|
|
public abstract class AbstractCollectionConverter implements Converter {
|
12
|
|
protected ClassMapper classMapper;
|
13
|
|
|
14
|
|
public abstract boolean canConvert(Class type);
|
15
|
|
|
16
|
105
|
public AbstractCollectionConverter(ClassMapper classMapper) {
|
17
|
105
|
this.classMapper = classMapper;
|
18
|
|
}
|
19
|
|
|
20
|
|
public abstract void toXML(ObjectTree objectGraph, XMLWriter xmlWriter, ConverterLookup converterLookup);
|
21
|
|
|
22
|
|
public abstract void fromXML(ObjectTree objectGraph, XMLReader xmlReader, ConverterLookup converterLookup, Class requiredType);
|
23
|
|
|
24
|
35
|
protected void writeItem(Object item, XMLWriter xmlWriter, ConverterLookup converterLookup, ObjectTree objectGraph) {
|
25
|
35
|
if (item == null) {
|
26
|
2
|
xmlWriter.startElement("null");
|
27
|
2
|
xmlWriter.endElement();
|
28
|
|
} else {
|
29
|
33
|
Class type = item.getClass();
|
30
|
33
|
xmlWriter.startElement(classMapper.lookupName(type));
|
31
|
33
|
Converter converter = converterLookup.lookupConverterForType(type);
|
32
|
33
|
converter.toXML(objectGraph.newStack(item), xmlWriter, converterLookup);
|
33
|
33
|
xmlWriter.endElement();
|
34
|
|
}
|
35
|
|
}
|
36
|
|
|
37
|
35
|
protected Object readItem(XMLReader xmlReader, int childIndex, ObjectTree objectGraph, ConverterLookup converterLookup) {
|
38
|
35
|
xmlReader.child(childIndex);
|
39
|
35
|
Class type = classMapper.lookupType(xmlReader.name());
|
40
|
35
|
ObjectTree itemWriter = objectGraph.newStack(type);
|
41
|
35
|
Converter converter = converterLookup.lookupConverterForType(type);
|
42
|
35
|
converter.fromXML(itemWriter, xmlReader, converterLookup, type);
|
43
|
35
|
xmlReader.pop();
|
44
|
35
|
return itemWriter.get();
|
45
|
|
}
|
46
|
|
|
47
|
12
|
protected Object createCollection(Class type) {
|
48
|
12
|
Class defaultType = classMapper.lookupDefaultType(type);
|
49
|
12
|
try {
|
50
|
12
|
return defaultType.newInstance();
|
51
|
|
} catch (InstantiationException e) {
|
52
|
0
|
throw new ConversionException("Cannot instantiate " + defaultType.getName(), e);
|
53
|
|
} catch (IllegalAccessException e) {
|
54
|
0
|
throw new ConversionException("Cannot instantiate " + defaultType.getName(), e);
|
55
|
|
}
|
56
|
|
}
|
57
|
|
}
|
58
|
|
|