1 19 20 package org.apache.cayenne.dataview; 21 22 import java.util.HashMap ; 23 import java.util.Iterator ; 24 import java.util.List ; 25 import java.util.Map ; 26 27 import org.apache.cayenne.DataObject; 28 29 33 public class LookupCache { 34 35 private Map fieldCache = new HashMap (); 36 private static final Object [] EMPTY_ARRAY = new Object [] {}; 37 38 public LookupCache() { 39 } 40 41 public void cache(ObjEntityViewField field, List dataObjects) { 42 Lookup lookup = getLookup(field); 43 if (lookup == null) { 44 lookup = new Lookup(); 45 fieldCache.put(field, lookup); 46 } 47 lookup.cache(field, dataObjects); 48 } 49 50 public void clear() { 51 fieldCache.clear(); 52 } 53 54 public boolean removeFromCache(ObjEntityViewField field) { 55 return fieldCache.remove(field) != null; 56 } 57 58 public Object [] getCachedValues(ObjEntityViewField field) { 59 Lookup lookup = getLookup(field); 60 Object [] values = (lookup != null ? lookup.values : EMPTY_ARRAY); 61 if (values.length == 0) 62 return values; 63 else { 64 Object [] valuesCopy = new Object [values.length]; 65 System.arraycopy(values, 0, valuesCopy, 0, values.length); 66 return valuesCopy; 67 } 68 } 69 70 public DataObject getDataObject(ObjEntityViewField field, Object value) { 71 Lookup lookup = getLookup(field); 72 if (lookup == null) 73 return null; 74 return lookup.getDataObject(value); 75 } 76 77 private Lookup getLookup(ObjEntityViewField field) { 78 if (field == null) 79 return null; 80 return (Lookup) fieldCache.get(field); 81 } 82 83 private class Lookup { 84 85 ObjEntityViewField field; 86 Object [] values = EMPTY_ARRAY; 87 Map valueDataObjectMap; 88 89 void cache(ObjEntityViewField field, List dataObjects) { 90 this.field = field; 91 if (values.length != dataObjects.size()) 92 values = new Object [dataObjects.size()]; 93 valueDataObjectMap = new HashMap (values.length + 1); 94 int index = 0; 95 for (Iterator i = dataObjects.iterator(); i.hasNext();) { 96 DataObject item = (DataObject) i.next(); 97 values[index] = field.getValue(item); 98 valueDataObjectMap.put(values[index], item); 99 index++; 100 } 101 } 102 103 DataObject getDataObject(Object value) { 104 return (DataObject) valueDataObjectMap.get(value); 105 } 106 } 107 } 108 | Popular Tags |