KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > mapper > FieldAliasingMapper


1 package com.thoughtworks.xstream.mapper;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4
5 import java.util.*;
6
7 /**
8  * Mapper that allows a field of a specific class to be replaced with a shorter alias, or omitted
9  * entirely.
10  *
11  * @author Joe Walnes
12  */

13 public class FieldAliasingMapper extends MapperWrapper {
14
15     protected final Map fieldToAliasMap = Collections.synchronizedMap(new HashMap());
16     protected final Map aliasToFieldMap = Collections.synchronizedMap(new HashMap());
17     protected final Set fieldsToOmit = Collections.synchronizedSet(new HashSet());
18
19     public FieldAliasingMapper(ClassMapper wrapped) {
20         super(wrapped);
21     }
22
23     public void addFieldAlias(String JavaDoc alias, Class JavaDoc type, String JavaDoc fieldName) {
24         fieldToAliasMap.put(key(type, fieldName), alias);
25         aliasToFieldMap.put(key(type, alias), fieldName);
26     }
27
28     private Object JavaDoc key(Class JavaDoc type, String JavaDoc value) {
29         return type.getName() + '.' + value;
30     }
31
32     public String JavaDoc serializedMember(Class JavaDoc type, String JavaDoc memberName) {
33         String JavaDoc alias = (String JavaDoc) fieldToAliasMap.get(key(type, memberName));
34         if (alias == null) {
35             return super.serializedMember(type, memberName);
36         } else {
37             return alias;
38         }
39     }
40
41     public String JavaDoc realMember(Class JavaDoc type, String JavaDoc serialized) {
42         String JavaDoc real = (String JavaDoc) aliasToFieldMap.get(key(type, serialized));
43         if (real == null) {
44             return super.realMember(type, serialized);
45         } else {
46             return real;
47         }
48     }
49
50     public boolean shouldSerializeMember(Class JavaDoc definedIn, String JavaDoc fieldName) {
51         return !fieldsToOmit.contains(key(definedIn, fieldName));
52     }
53
54     public void omitField(Class JavaDoc type, String JavaDoc fieldName) {
55         fieldsToOmit.add(key(type, fieldName));
56     }
57 }
58
Popular Tags