1 16 package org.apache.commons.collections.map; 17 18 import java.io.IOException ; 19 import java.io.ObjectInputStream ; 20 import java.io.ObjectOutputStream ; 21 import java.io.Serializable ; 22 import java.util.Iterator ; 23 import java.util.Map ; 24 25 import org.apache.commons.collections.Transformer; 26 27 42 public class TransformedMap 43 extends AbstractInputCheckedMapDecorator 44 implements Serializable { 45 46 47 private static final long serialVersionUID = 7023152376788900464L; 48 49 50 protected final Transformer keyTransformer; 51 52 protected final Transformer valueTransformer; 53 54 65 public static Map decorate(Map map, Transformer keyTransformer, Transformer valueTransformer) { 66 return new TransformedMap(map, keyTransformer, valueTransformer); 67 } 68 69 81 protected TransformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) { 82 super(map); 83 this.keyTransformer = keyTransformer; 84 this.valueTransformer = valueTransformer; 85 } 86 87 95 private void writeObject(ObjectOutputStream out) throws IOException { 96 out.defaultWriteObject(); 97 out.writeObject(map); 98 } 99 100 108 private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException { 109 in.defaultReadObject(); 110 map = (Map ) in.readObject(); 111 } 112 113 122 protected Object transformKey(Object object) { 123 if (keyTransformer == null) { 124 return object; 125 } 126 return keyTransformer.transform(object); 127 } 128 129 137 protected Object transformValue(Object object) { 138 if (valueTransformer == null) { 139 return object; 140 } 141 return valueTransformer.transform(object); 142 } 143 144 152 protected Map transformMap(Map map) { 153 Map result = new LinkedMap(map.size()); 154 for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) { 155 Map.Entry entry = (Map.Entry ) it.next(); 156 result.put(transformKey(entry.getKey()), transformValue(entry.getValue())); 157 } 158 return result; 159 } 160 161 168 protected Object checkSetValue(Object value) { 169 return valueTransformer.transform(value); 170 } 171 172 178 protected boolean isSetValueChecking() { 179 return (valueTransformer != null); 180 } 181 182 public Object put(Object key, Object value) { 184 key = transformKey(key); 185 value = transformValue(value); 186 return getMap().put(key, value); 187 } 188 189 public void putAll(Map mapToCopy) { 190 mapToCopy = transformMap(mapToCopy); 191 getMap().putAll(mapToCopy); 192 } 193 194 } 195 | Popular Tags |