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 ; 13 import java.io.StringReader ; 14 15 public class DataHolderTest extends AbstractAcceptanceTest { 16 17 class StringWithPrefixConverter implements Converter { 18 19 public boolean canConvert(Class type) { 20 return type == String .class; 21 } 22 23 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 24 String prefix = (String ) context.get("prefix"); 25 if (prefix != null) { 26 writer.addAttribute("prefix", prefix); 27 } 28 writer.setValue(source.toString()); 29 } 30 31 public Object 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 xstream.registerConverter(new StringWithPrefixConverter()); 41 StringWriter writer = new StringWriter (); 42 DataHolder dataHolder = xstream.newDataHolder(); 43 44 dataHolder.put("prefix", "additional stuff"); 46 xstream.marshal("something", new PrettyPrintWriter(writer), dataHolder); 47 48 String expected = "<string prefix=\"additional stuff\">something</string>"; 50 assertEquals(expected, writer.toString()); 51 } 52 53 public void testCanBePassedInToUnmarshallerExternally() { 54 xstream.registerConverter(new StringWithPrefixConverter()); 56 DataHolder dataHolder = xstream.newDataHolder(); 57 58 String xml = "<string can-you-see-me=\"yes\">something</string>"; 60 Object result = xstream.unmarshal(new XppReader(new StringReader (xml)), null, dataHolder); 61 62 assertEquals("something", result); 64 assertEquals("yes", dataHolder.get("saw-this")); 65 } 66 67 68 } 69 | Popular Tags |