01: /*
02: * Copyright (C) 2004 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 04. October 2004 by Joe Walnes
11: */
12: package com.thoughtworks.acceptance;
13:
14: import com.thoughtworks.xstream.converters.Converter;
15: import com.thoughtworks.xstream.converters.DataHolder;
16: import com.thoughtworks.xstream.converters.MarshallingContext;
17: import com.thoughtworks.xstream.converters.UnmarshallingContext;
18: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
19: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
20: import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
21: import com.thoughtworks.xstream.io.xml.XppReader;
22:
23: import java.io.StringReader;
24: import java.io.StringWriter;
25:
26: public class DataHolderTest extends AbstractAcceptanceTest {
27:
28: class StringWithPrefixConverter implements Converter {
29:
30: public boolean canConvert(Class type) {
31: return type == String.class;
32: }
33:
34: public void marshal(Object source,
35: HierarchicalStreamWriter writer,
36: MarshallingContext context) {
37: String prefix = (String) context.get("prefix");
38: if (prefix != null) {
39: writer.addAttribute("prefix", prefix);
40: }
41: writer.setValue(source.toString());
42: }
43:
44: public Object unmarshal(HierarchicalStreamReader reader,
45: UnmarshallingContext context) {
46: context.put("saw-this", reader
47: .getAttribute("can-you-see-me"));
48: return reader.getValue();
49: }
50:
51: }
52:
53: public void testCanBePassedInToMarshallerExternally() {
54: // setup
55: xstream.registerConverter(new StringWithPrefixConverter());
56: StringWriter writer = new StringWriter();
57: DataHolder dataHolder = xstream.newDataHolder();
58:
59: // execute
60: dataHolder.put("prefix", "additional stuff");
61: xstream.marshal("something", new PrettyPrintWriter(writer),
62: dataHolder);
63:
64: // verify
65: String expected = "<string prefix=\"additional stuff\">something</string>";
66: assertEquals(expected, writer.toString());
67: }
68:
69: public void testCanBePassedInToUnmarshallerExternally() {
70: // setup
71: xstream.registerConverter(new StringWithPrefixConverter());
72: DataHolder dataHolder = xstream.newDataHolder();
73:
74: // execute
75: String xml = "<string can-you-see-me=\"yes\">something</string>";
76: Object result = xstream.unmarshal(new XppReader(
77: new StringReader(xml)), null, dataHolder);
78:
79: // verify
80: assertEquals("something", result);
81: assertEquals("yes", dataHolder.get("saw-this"));
82: }
83:
84: }
|