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.sql.SQLException ; 38 import java.util.AbstractList ; 39 import java.util.ArrayList ; 40 import java.util.Collection ; 41 import java.util.Iterator ; 42 43 46 public class CollectionImpl<E> extends AbstractList <E> 47 implements AmberCollection { 48 private AmberQuery _query; 49 50 private AmberConnection _aConn; 51 52 private ArrayList <E> _values = new ArrayList <E>(); 53 private long _expireTime; 54 55 public CollectionImpl(AmberConnection aConn, String query) 56 { 57 _aConn = aConn; 58 59 if (query != null) { 61 try { 62 _query = _aConn.prepareQuery(query); 63 } catch (SQLException e) { 64 throw new AmberRuntimeException(e); 65 } 66 } 67 } 68 69 public CollectionImpl(AmberQuery query) 70 { 71 _query = query; 72 73 setSession(((UserQuery) _query).getConnection()); 74 } 75 76 79 public void setSession(AmberConnection aConn) 80 { 81 _aConn = aConn; 82 83 if (_aConn != null) 84 _aConn.register(this); 85 } 86 87 90 public AmberQuery getQuery() 91 { 92 return _query; 93 } 94 95 98 public int size() 99 { 100 fill(); 101 102 return _values.size(); 103 } 104 105 108 public Iterator <E> iterator() 109 { 110 fill(); 111 112 return new ValuesIterator(_values); 113 } 114 115 118 public E get(int index) 119 { 120 fill(); 121 122 return _values.get(index); 123 } 124 125 128 public boolean add(E o) 129 { 130 fill(); 131 132 return _values.add(o); 133 } 134 135 138 public boolean addAll(int index, 139 Collection <? extends E> collection) 140 { 141 fill(); 142 143 return _values.addAll(index, collection); 144 } 145 146 149 public void clear() 150 { 151 _values.clear(); 152 _expireTime = Alarm.getCurrentTime(); 153 } 154 155 158 public void update() 159 { 160 _expireTime = 0; 161 } 162 163 protected boolean isValid() 164 { 165 return Alarm.getCurrentTime() <= _expireTime; 166 } 167 168 private void fill() 169 { 170 if (_query == null) 172 return; 173 174 if (Alarm.getCurrentTime() <= _expireTime) 175 return; 176 177 try { 178 _expireTime = Alarm.getCurrentTime(); 179 180 ((UserQuery) _query).setSession(_aConn); 181 _values.clear(); 182 _query.list((ArrayList ) _values); 183 } catch (SQLException e) { 184 throw new AmberRuntimeException(e); 185 } 186 } 187 188 class ValuesIterator implements Iterator { 189 private ArrayList <E> _values; 190 private int i = 0; 191 192 ValuesIterator(ArrayList <E> values) 193 { 194 _values = new ArrayList <E>(values); 195 } 196 197 public boolean hasNext() 198 { 199 return i < _values.size(); 200 } 201 202 public E next() 203 { 204 if (i < _values.size()) 205 return _values.get(i++); 206 else 207 return null; 208 } 209 210 public void remove() 211 { 212 CollectionImpl.this.remove(_values.get(i - 1)); 213 } 214 } 215 } 216 | Popular Tags |