1 package org.sapia.util.cursor.impl; 2 3 import java.util.ArrayList ; 4 import java.util.List ; 5 import java.util.NoSuchElementException ; 6 7 import org.sapia.util.cursor.Batch; 8 import org.sapia.util.cursor.Cursor; 9 import org.sapia.util.cursor.CursorException; 10 import org.sapia.util.cursor.CursorFeed; 11 import org.sapia.util.cursor.CursorListener; 12 13 22 public class CursorImpl implements Cursor{ 23 24 private int _batchSize; 25 private List _batches = new ArrayList (20); 26 private int _pos, _totalCount; 27 private boolean _finished; 28 private CursorFeed _feed; 29 private Batch _currentBatch; 30 private CursorListener _listener; 31 32 38 public CursorImpl(CursorFeed feed, CursorListener listener, int batchSize){ 39 _batchSize = batchSize; 40 _feed = feed; 41 _listener = listener; 42 } 43 44 47 public int getBatchCount() { 48 return _batches.size(); 49 } 50 51 54 public int getItemCount() { 55 return _totalCount; 56 } 57 58 62 public int getBatchSize(){ 63 return _batchSize; 64 } 65 66 69 public Batch getCurrentBatch(){ 70 if(_currentBatch == null){ 71 throw new NoSuchElementException (); 72 } 73 return _currentBatch; 74 } 75 76 79 public boolean hasNextBatch(){ 80 if(_finished){ 81 return false; 82 } 83 else if(_pos >= _batches.size()){ 84 Object [] items = newItems(); 85 int count = 0; 86 try{ 87 count = _feed.read(items); 88 }catch(Exception e){ 89 throw new CursorException("Could not feed", e); 90 } 91 if(count == 0){ 92 _finished = true; 93 return false; 94 } 95 Batch b = new BatchImpl(items, _listener, count, _totalCount); 96 _batches.add(b); 97 _totalCount = _totalCount+count; 98 return true; 99 } 100 else{ 101 return true; 102 } 103 } 104 105 108 public boolean hasPreviousBatch(){ 109 return _pos > 0; 110 } 111 112 115 public Batch nextBatch(){ 116 if(_pos >= _batches.size()){ 117 throw new NoSuchElementException (); 118 } 119 return _currentBatch = (Batch)_batches.get(_pos++); 120 } 121 122 125 public Batch previousBatch(){ 126 if(_pos <= 0){ 127 throw new NoSuchElementException (); 128 } 129 if(_pos >= _batches.size()){ 130 _pos--; 131 } 132 return _currentBatch = (Batch)_batches.get(_pos--); 133 } 134 135 138 public Cursor toLast(){ 139 if(_batches.size() > 0) 140 _pos = _batches.size() - 1; 141 return this; 142 } 143 144 147 public Cursor toFirst(){ 148 _pos = 0; 149 return this; 150 } 151 152 155 public int available() { 156 try{ 157 return _feed.available(); 158 }catch(Exception e){ 159 throw new CursorException("Could not poll underlying feed", e); 160 } 161 } 162 163 166 public void close() { 167 _feed.close(); 168 } 169 170 private Object [] newItems(){ 171 return new Object [_batchSize]; 172 } 173 } 174 | Popular Tags |