1 package com.thoughtworks.acceptance; 2 3 import com.thoughtworks.xstream.XStream; 4 import com.thoughtworks.xstream.alias.ClassMapper; 5 import com.thoughtworks.xstream.mapper.MapperWrapper; 6 import com.thoughtworks.acceptance.objects.Software; 7 8 public class CustomMapperTest extends AbstractAcceptanceTest { 9 10 13 private static class FieldPrefixStrippingMapper extends MapperWrapper { 14 public FieldPrefixStrippingMapper(ClassMapper wrapped) { 15 super(wrapped); 16 } 17 18 public String serializedMember(Class type, String memberName) { 19 if (memberName.startsWith("_")) { 20 memberName = memberName.substring(1); } else if (memberName.startsWith("my")) { 23 memberName = memberName.substring(2, 3).toLowerCase() + memberName.substring(3); 25 } 26 return super.serializedMember(type, memberName); 27 } 28 29 public String realMember(Class type, String serialized) { 30 String fieldName = super.realMember(type, serialized); 31 try { 34 type.getDeclaredField("_" + fieldName); 35 return "_" + fieldName; 36 } catch (NoSuchFieldException e) { 37 try { 38 String myified = "my" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 39 type.getDeclaredField(myified); 40 return myified; 41 } catch (NoSuchFieldException e2) { 42 return fieldName; 43 } 44 } 45 } 46 } 47 48 public static class ThingWithStupidNamingConventions extends StandardObject { 49 String _firstName; 50 String lastName; 51 int myAge; 52 53 public ThingWithStupidNamingConventions(String firstname, String lastname, int age) { 54 _firstName = firstname; 55 this.lastName = lastname; 56 myAge = age; 57 } 58 } 59 60 public void testUserDefinedMappingCanAlterFieldName() { 61 xstream = new XStream() { 62 protected MapperWrapper wrapMapper(MapperWrapper next) { 63 return new FieldPrefixStrippingMapper(next); 64 } 65 }; 66 xstream.alias("thing", ThingWithStupidNamingConventions.class); 67 68 ThingWithStupidNamingConventions in = new ThingWithStupidNamingConventions("Joe", "Walnes", 10); 69 String expectedXml = "" 70 + "<thing>\n" 71 + " <firstName>Joe</firstName>\n" + " <lastName>Walnes</lastName>\n" 73 + " <age>10</age>\n" 74 + "</thing>"; 75 76 assertBothWays(in, expectedXml); 77 } 78 79 private static class PackageStrippingMapper extends MapperWrapper { 80 public PackageStrippingMapper(ClassMapper wrapped) { 81 super(wrapped); 82 } 83 84 public String serializedClass(Class type) { 85 return type.getName().replaceFirst(".*\\.", ""); 86 } 87 } 88 89 public void testStripsPackagesUponDeserialization() { 90 xstream = new XStream() { 92 protected MapperWrapper wrapMapper(MapperWrapper next) { 93 return new PackageStrippingMapper(next); 94 } 95 }; 96 97 99 String expectedXml = "" + 100 "<Software>\n" + 101 " <vendor>ms</vendor>\n" + 102 " <name>word</name>\n" + 103 "</Software>"; 104 assertEquals(expectedXml, xstream.toXML(new Software("ms", "word"))); 105 } 106 } 107 | Popular Tags |