1 28 29 package com.caucho.amber.collection; 30 31 import com.caucho.amber.AmberQuery; 32 import com.caucho.amber.AmberRuntimeException; 33 import com.caucho.amber.manager.AmberConnection; 34 import com.caucho.amber.query.UserQuery; 35 import com.caucho.util.Alarm; 36 37 import java.lang.reflect.Method ; 38 import java.sql.SQLException ; 39 import java.util.AbstractMap ; 40 import java.util.HashMap ; 41 import java.util.Map ; 42 import java.util.Set ; 43 44 47 public class MapImpl<K, V> extends AbstractMap <K, V> 48 implements AmberCollection { 49 private AmberQuery _query; 50 51 private AmberConnection _aConn; 52 53 private HashMap <K, V> _values = new HashMap <K, V>(); 54 private long _expireTime; 55 56 private Method _methodGetMapKey; 57 58 public MapImpl(AmberConnection aConn, 59 String query, 60 Method methodGetMapKey) 61 { 62 _aConn = aConn; 63 _methodGetMapKey = methodGetMapKey; 64 65 try { 66 _query = _aConn.prepareQuery(query); 67 } catch (SQLException e) { 68 throw new AmberRuntimeException(e); 69 } 70 } 71 72 public MapImpl(AmberQuery query, 73 Method methodGetMapKey) 74 { 75 _query = query; 76 _methodGetMapKey = methodGetMapKey; 77 78 setSession(((UserQuery) _query).getConnection()); 79 } 80 81 84 public void setSession(AmberConnection aConn) 85 { 86 _aConn = aConn; 87 88 _aConn.register(this); 89 } 90 91 94 public AmberQuery getQuery() 95 { 96 return _query; 97 } 98 99 102 public int size() 103 { 104 fill(); 105 106 return _values.size(); 107 } 108 109 112 public Set <Map.Entry <K, V>> entrySet() 113 { 114 fill(); 115 116 return _values.entrySet(); 117 } 118 119 122 public V get(Object key) 123 { 124 fill(); 125 126 return _values.get(key); 127 } 128 129 132 public Set <K> keySet() 133 { 134 fill(); 135 136 return _values.keySet(); 137 } 138 139 142 public void clear() 143 { 144 _values.clear(); 145 _expireTime = Alarm.getCurrentTime(); 146 } 147 148 151 public void update() 152 { 153 _expireTime = 0; 154 } 155 156 protected boolean isValid() 157 { 158 return Alarm.getCurrentTime() <= _expireTime; 159 } 160 161 private void fill() 162 { 163 if (Alarm.getCurrentTime() <= _expireTime) 164 return; 165 166 try { 167 _expireTime = Alarm.getCurrentTime(); 168 169 ((UserQuery) _query).setSession(_aConn); 170 _values.clear(); 171 _query.list((HashMap ) _values, _methodGetMapKey); 172 } catch (Exception e) { 173 throw new AmberRuntimeException(e); 174 } 175 } 176 } 177 | Popular Tags |