1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package pl.edu.agh.cast.backward.resources.xml;
19
20 import java.util.SortedMap;
21 import java.util.TreeMap;
22
23 import pl.edu.agh.cast.model.attributes.Attribute;
24 import pl.edu.agh.cast.model.attributes.AttributeValue;
25
26 import com.thoughtworks.xstream.converters.Converter;
27 import com.thoughtworks.xstream.converters.MarshallingContext;
28 import com.thoughtworks.xstream.converters.UnmarshallingContext;
29 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
30 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
31
32
33
34
35
36
37 public class AttributeValuesConverter implements Converter {
38
39 private static final String VALUE_NODE_NAME = "value";
40
41
42
43
44
45
46
47
48 @SuppressWarnings("unchecked")
49 public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
50
51 SortedMap<Attribute, AttributeValue> map = (SortedMap<Attribute, AttributeValue>)value;
52 for (AttributeValue elem : map.values()) {
53 writer.startNode(VALUE_NODE_NAME);
54 context.convertAnother(elem.getAttribute());
55 if (null != elem.getValue()) {
56 context.convertAnother(elem.getValue());
57 }
58 writer.endNode();
59 }
60
61 }
62
63
64
65
66
67
68
69
70 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
71
72 SortedMap<Attribute, AttributeValue> map = new TreeMap<Attribute, AttributeValue>();
73
74 while (reader.hasMoreChildren()) {
75 reader.moveDown();
76 Attribute attribute = (Attribute)context.convertAnother(map, Attribute.class);
77 String text = reader.getValue();
78 Object value = null;
79 if (text.length() > 0) {
80 value = attribute.getType().getValidator().convertFromStringFormat(text);
81 }
82 map.put(attribute, new AttributeValue(attribute, value));
83 reader.moveUp();
84 }
85
86 return map;
87 }
88
89
90
91
92
93
94 @SuppressWarnings("unchecked")
95 public boolean canConvert(Class arg0) {
96 return SortedMap.class.isAssignableFrom(arg0);
97 }
98
99 }