1 56 package org.objectstyle.cayenne.dataview; 57 58 import java.util.HashMap ; 59 import java.util.Iterator ; 60 import java.util.List ; 61 import java.util.Map ; 62 63 import org.objectstyle.cayenne.DataObject; 64 65 69 public class LookupCache { 70 71 private Map fieldCache = new HashMap (); 72 private static final Object [] EMPTY_ARRAY = new Object [] {}; 73 74 public LookupCache() { 75 } 76 77 public void cache(ObjEntityViewField field, List dataObjects) { 78 Lookup lookup = getLookup(field); 79 if (lookup == null) { 80 lookup = new Lookup(); 81 fieldCache.put(field, lookup); 82 } 83 lookup.cache(field, dataObjects); 84 } 85 86 public void clear() { 87 fieldCache.clear(); 88 } 89 90 public boolean removeFromCache(ObjEntityViewField field) { 91 return fieldCache.remove(field) != null; 92 } 93 94 public Object [] getCachedValues(ObjEntityViewField field) { 95 Lookup lookup = getLookup(field); 96 Object [] values = (lookup != null ? lookup.values : EMPTY_ARRAY); 97 if (values.length == 0) 98 return values; 99 else { 100 Object [] valuesCopy = new Object [values.length]; 101 System.arraycopy(values, 0, valuesCopy, 0, values.length); 102 return valuesCopy; 103 } 104 } 105 106 public DataObject getDataObject(ObjEntityViewField field, Object value) { 107 Lookup lookup = getLookup(field); 108 if (lookup == null) 109 return null; 110 return lookup.getDataObject(value); 111 } 112 113 private Lookup getLookup(ObjEntityViewField field) { 114 if (field == null) 115 return null; 116 return (Lookup) fieldCache.get(field); 117 } 118 119 private class Lookup { 120 121 ObjEntityViewField field; 122 Object [] values = EMPTY_ARRAY; 123 Map valueDataObjectMap; 124 125 void cache(ObjEntityViewField field, List dataObjects) { 126 this.field = field; 127 if (values.length != dataObjects.size()) 128 values = new Object [dataObjects.size()]; 129 valueDataObjectMap = new HashMap (values.length + 1); 130 int index = 0; 131 for (Iterator i = dataObjects.iterator(); i.hasNext();) { 132 DataObject item = (DataObject) i.next(); 133 values[index] = field.getValue(item); 134 valueDataObjectMap.put(values[index], item); 135 index++; 136 } 137 } 138 139 DataObject getDataObject(Object value) { 140 return (DataObject) valueDataObjectMap.get(value); 141 } 142 } 143 } | Popular Tags |