01: /*
02: * Copyright (C) 2005 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 09. April 2005 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.mapper;
13:
14: import com.thoughtworks.xstream.alias.ClassMapper;
15:
16: import java.util.HashMap;
17: import java.util.HashSet;
18: import java.util.Map;
19: import java.util.Set;
20:
21: /**
22: * Mapper that allows a field of a specific class to be replaced with a shorter alias, or omitted
23: * entirely.
24: *
25: * @author Joe Walnes
26: */
27: public class FieldAliasingMapper extends MapperWrapper {
28:
29: protected final Map fieldToAliasMap = new HashMap();
30: protected final Map aliasToFieldMap = new HashMap();
31: protected final Set fieldsToOmit = new HashSet();
32:
33: public FieldAliasingMapper(Mapper wrapped) {
34: super (wrapped);
35: }
36:
37: /**
38: * @deprecated As of 1.2, use {@link #FieldAliasingMapper(Mapper)}
39: */
40: public FieldAliasingMapper(ClassMapper wrapped) {
41: this ((Mapper) wrapped);
42: }
43:
44: public void addFieldAlias(String alias, Class type, String fieldName) {
45: fieldToAliasMap.put(key(type, fieldName), alias);
46: aliasToFieldMap.put(key(type, alias), fieldName);
47: }
48:
49: private Object key(Class type, String name) {
50: return type.getName() + ':' + name;
51: }
52:
53: public String serializedMember(Class type, String memberName) {
54: String alias = getMember(type, memberName, fieldToAliasMap);
55: if (alias == null) {
56: return super .serializedMember(type, memberName);
57: } else {
58: return alias;
59: }
60: }
61:
62: public String realMember(Class type, String serialized) {
63: String real = getMember(type, serialized, aliasToFieldMap);
64: if (real == null) {
65: return super .realMember(type, serialized);
66: } else {
67: return real;
68: }
69: }
70:
71: private String getMember(Class type, String name, Map map) {
72: String member = null;
73: for (Class declaringType = type; member == null
74: && declaringType != Object.class; declaringType = declaringType
75: .getSuperclass()) {
76: member = (String) map.get(key(declaringType, name));
77: }
78: return member;
79: }
80:
81: public boolean shouldSerializeMember(Class definedIn,
82: String fieldName) {
83: return !fieldsToOmit.contains(key(definedIn, fieldName));
84: }
85:
86: public void omitField(Class definedIn, String fieldName) {
87: fieldsToOmit.add(key(definedIn, fieldName));
88: }
89: }
|