1 package com.thoughtworks.xstream.converters.composite;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.converters.Converter;
5 import com.thoughtworks.xstream.converters.ConverterLookup;
6 import com.thoughtworks.xstream.objecttree.ObjectTree;
7 import com.thoughtworks.xstream.xml.XMLReader;
8 import com.thoughtworks.xstream.xml.XMLWriter;
9
10 public class ObjectWithFieldsConverter implements Converter {
11
12 private ClassMapper classMapper;
13
14 public ObjectWithFieldsConverter(ClassMapper classMapper) {
15 this.classMapper = classMapper;
16 }
17
18 public boolean canConvert(Class type) {
19 return true;
20 }
21
22 public void toXML(ObjectTree objectGraph, XMLWriter xmlWriter, ConverterLookup converterLookup) {
23 String[] fieldNames = objectGraph.fieldNames();
24 for (int i = 0; i < fieldNames.length; i++) {
25 String fieldName = fieldNames[i];
26
27 objectGraph.push(fieldName);
28
29 if (objectGraph.get() != null) {
30 writeFieldAsXML(xmlWriter, fieldName, objectGraph, converterLookup);
31 }
32
33 objectGraph.pop();
34 }
35 }
36
37 private void writeFieldAsXML(XMLWriter xmlWriter, String fieldName, ObjectTree objectGraph, ConverterLookup converterLookup) {
38 xmlWriter.startElement(fieldName);
39
40 writeClassAttributeInXMLIfNotDefaultImplementation(objectGraph, xmlWriter);
41 Converter converter = converterLookup.lookupConverterForType(objectGraph.type());
42 converter.toXML(objectGraph, xmlWriter, converterLookup);
43
44 xmlWriter.endElement();
45 }
46
47 protected void writeClassAttributeInXMLIfNotDefaultImplementation(ObjectTree objectGraph, XMLWriter xmlWriter) {
48 Class actualType = objectGraph.get().getClass();
49 Class defaultType = classMapper.lookupDefaultType(objectGraph.type());
50 if (!actualType.equals(defaultType)) {
51 xmlWriter.addAttribute("class", classMapper.lookupName(actualType));
52 }
53 }
54
55 public void fromXML(final ObjectTree objectGraph, XMLReader xmlReader, ConverterLookup converterLookup, Class requiredType) {
56 objectGraph.create(requiredType);
57 String[] fieldNames = objectGraph.fieldNames();
58 for (int i = 0; i < fieldNames.length; i++) {
59 String fieldName = fieldNames[i];
60 if (xmlReader.childExists(fieldName)) {
61 objectGraph.push(fieldName);
62 xmlReader.child(fieldName);
63
64 Class type = determineWhichImplementationToUse(xmlReader, objectGraph);
65 Converter converter = converterLookup.lookupConverterForType(type);
66 converter.fromXML(objectGraph, xmlReader, converterLookup, type);
67
68 xmlReader.pop();
69 objectGraph.pop();
70 }
71 }
72 }
73
74 private Class determineWhichImplementationToUse(XMLReader xmlReader, final ObjectTree objectGraph) {
75 String classAttribute = xmlReader.attribute("class");
76 Class type;
77 if (classAttribute == null) {
78 type = objectGraph.type();
79 } else {
80 type = classMapper.lookupType(classAttribute);
81 }
82 return type;
83 }
84
85 }
This page was automatically generated by Maven