KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > acceptance > DataHolderTest


1 package com.thoughtworks.acceptance;
2
3 import com.thoughtworks.xstream.converters.Converter;
4 import com.thoughtworks.xstream.converters.DataHolder;
5 import com.thoughtworks.xstream.converters.MarshallingContext;
6 import com.thoughtworks.xstream.converters.UnmarshallingContext;
7 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
9 import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
10 import com.thoughtworks.xstream.io.xml.XppReader;
11
12 import java.io.StringWriter JavaDoc;
13 import java.io.StringReader JavaDoc;
14
15 public class DataHolderTest extends AbstractAcceptanceTest {
16
17     class StringWithPrefixConverter implements Converter {
18
19         public boolean canConvert(Class JavaDoc type) {
20             return type == String JavaDoc.class;
21         }
22
23         public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
24             String JavaDoc prefix = (String JavaDoc) context.get("prefix");
25             if (prefix != null) {
26                 writer.addAttribute("prefix", prefix);
27             }
28             writer.setValue(source.toString());
29         }
30
31         public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
32             context.put("saw-this", reader.getAttribute("can-you-see-me"));
33             return reader.getValue();
34         }
35
36     }
37
38     public void testCanBePassedInToMarshallerExternally() {
39         // setup
40
xstream.registerConverter(new StringWithPrefixConverter());
41         StringWriter JavaDoc writer = new StringWriter JavaDoc();
42         DataHolder dataHolder = xstream.newDataHolder();
43
44         // execute
45
dataHolder.put("prefix", "additional stuff");
46         xstream.marshal("something", new PrettyPrintWriter(writer), dataHolder);
47
48         // verify
49
String JavaDoc expected = "<string prefix=\"additional stuff\">something</string>";
50         assertEquals(expected, writer.toString());
51     }
52
53     public void testCanBePassedInToUnmarshallerExternally() {
54         // setup
55
xstream.registerConverter(new StringWithPrefixConverter());
56         DataHolder dataHolder = xstream.newDataHolder();
57
58         // execute
59
String JavaDoc xml = "<string can-you-see-me=\"yes\">something</string>";
60         Object JavaDoc result = xstream.unmarshal(new XppReader(new StringReader JavaDoc(xml)), null, dataHolder);
61
62         // verify
63
assertEquals("something", result);
64         assertEquals("yes", dataHolder.get("saw-this"));
65     }
66
67
68 }
69
Popular Tags