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.Predicate; 26 27 46 public class PredicatedMap 47 extends AbstractInputCheckedMapDecorator 48 implements Serializable { 49 50 51 private static final long serialVersionUID = 7412622456128415156L; 52 53 54 protected final Predicate keyPredicate; 55 56 protected final Predicate valuePredicate; 57 58 69 public static Map decorate(Map map, Predicate keyPredicate, Predicate valuePredicate) { 70 return new PredicatedMap(map, keyPredicate, valuePredicate); 71 } 72 73 82 protected PredicatedMap(Map map, Predicate keyPredicate, Predicate valuePredicate) { 83 super(map); 84 this.keyPredicate = keyPredicate; 85 this.valuePredicate = valuePredicate; 86 87 Iterator it = map.entrySet().iterator(); 88 while (it.hasNext()) { 89 Map.Entry entry = (Map.Entry ) it.next(); 90 Object key = entry.getKey(); 91 Object value = entry.getValue(); 92 validate(key, value); 93 } 94 } 95 96 104 private void writeObject(ObjectOutputStream out) throws IOException { 105 out.defaultWriteObject(); 106 out.writeObject(map); 107 } 108 109 117 private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException { 118 in.defaultReadObject(); 119 map = (Map ) in.readObject(); 120 } 121 122 130 protected void validate(Object key, Object value) { 131 if (keyPredicate != null && keyPredicate.evaluate(key) == false) { 132 throw new IllegalArgumentException ("Cannot add key - Predicate rejected it"); 133 } 134 if (valuePredicate != null && valuePredicate.evaluate(value) == false) { 135 throw new IllegalArgumentException ("Cannot add value - Predicate rejected it"); 136 } 137 } 138 139 146 protected Object checkSetValue(Object value) { 147 if (valuePredicate.evaluate(value) == false) { 148 throw new IllegalArgumentException ("Cannot set value - Predicate rejected it"); 149 } 150 return value; 151 } 152 153 159 protected boolean isSetValueChecking() { 160 return (valuePredicate != null); 161 } 162 163 public Object put(Object key, Object value) { 165 validate(key, value); 166 return map.put(key, value); 167 } 168 169 public void putAll(Map mapToCopy) { 170 Iterator it = mapToCopy.entrySet().iterator(); 171 while (it.hasNext()) { 172 Map.Entry entry = (Map.Entry ) it.next(); 173 Object key = entry.getKey(); 174 Object value = entry.getValue(); 175 validate(key, value); 176 } 177 map.putAll(mapToCopy); 178 } 179 180 } 181 | Popular Tags |