1 29 30 package com.caucho.amber.collection; 31 32 import com.caucho.amber.AmberQuery; 33 import com.caucho.amber.AmberRuntimeException; 34 import com.caucho.amber.manager.AmberConnection; 35 import com.caucho.amber.query.UserQuery; 36 import com.caucho.util.Alarm; 37 38 import java.sql.SQLException ; 39 import java.util.AbstractSet ; 40 import java.util.ArrayList ; 41 import java.util.Collection ; 42 import java.util.Iterator ; 43 44 47 public class SetImpl<E> extends AbstractSet <E> 48 implements AmberCollection { 49 private AmberQuery _query; 50 51 private AmberConnection _aConn; 52 53 private ArrayList <E> _values = new ArrayList <E>(); 54 private long _expireTime; 55 56 public SetImpl(AmberConnection aConn, String query) 57 { 58 _aConn = aConn; 59 60 try { 61 _query = _aConn.prepareQuery(query); 62 } catch (SQLException e) { 63 throw new AmberRuntimeException(e); 64 } 65 } 66 67 public SetImpl(AmberQuery query) 68 { 69 _query = query; 70 71 setSession(((UserQuery) _query).getConnection()); 72 } 73 74 77 public void setSession(com.caucho.amber.AmberConnection aConn) 78 { 79 throw new UnsupportedOperationException (); 80 } 82 83 86 public void setSession(AmberConnection aConn) 87 { 88 _aConn = aConn; 89 90 _aConn.register(this); 91 } 92 93 96 public AmberQuery getQuery() 97 { 98 return _query; 99 } 100 101 104 public int size() 105 { 106 fill(); 107 108 return _values.size(); 109 } 110 111 114 public Iterator iterator() 115 { 116 fill(); 117 118 return new ValuesIterator(_values); 119 } 120 121 124 public E get(int index) 125 { 126 fill(); 127 128 return _values.get(index); 129 } 130 131 134 public boolean addAll(Collection <? extends E> collection) 135 { 136 fill(); 137 138 return _values.addAll(collection); 139 } 140 141 144 public void clear() 145 { 146 _values.clear(); 147 _expireTime = Alarm.getCurrentTime(); 148 } 149 150 153 public void update() 154 { 155 _expireTime = 0; 156 } 157 158 protected boolean isValid() 159 { 160 return Alarm.getCurrentTime() <= _expireTime; 161 } 162 163 private void fill() 164 { 165 if (Alarm.getCurrentTime() <= _expireTime) 166 return; 167 168 try { 169 _expireTime = Alarm.getCurrentTime(); 170 171 ((UserQuery) _query).setSession(_aConn); 172 _values.clear(); 173 _query.list((ArrayList ) _values); 174 } catch (SQLException e) { 175 throw new AmberRuntimeException(e); 176 } 177 } 178 179 class ValuesIterator implements Iterator { 180 private ArrayList <E> _values; 181 private int i = 0; 182 183 ValuesIterator(ArrayList <E> values) 184 { 185 _values = new ArrayList <E>(values); 186 } 187 188 public boolean hasNext() 189 { 190 return i < _values.size(); 191 } 192 193 public Object next() 194 { 195 if (i < _values.size()) 196 return _values.get(i++); 197 else 198 return null; 199 } 200 201 public void remove() 202 { 203 SetImpl.this.remove(_values.get(i - 1)); 204 } 205 } 206 } 207 | Popular Tags |