1 package org.sapia.util.cursor.impl; 2 3 import org.sapia.util.cursor.Batch; 4 import org.sapia.util.cursor.CursorException; 5 import org.sapia.util.cursor.CursorListener; 6 7 16 public class BatchImpl implements Batch{ 17 18 private Object [] _items; 19 private int _count, _index; 20 private CursorListener _listener; 21 private int _pos; 22 23 29 public BatchImpl(Object [] items, CursorListener listener, int count, int absoluteIndex){ 30 _items = items; 31 _listener = listener; 32 _count = count; 33 _index = absoluteIndex; 34 } 35 36 39 public int getCount(){ 40 return _count; 41 } 42 43 46 public int getAbsolutePos(){ 47 return _index + _pos; 48 } 49 50 53 public int getPos(){ 54 return _pos; 55 } 56 57 60 public void setPos(int pos){ 61 if(_count == 0 || pos < 0 || pos >= _count){ 62 throw new IndexOutOfBoundsException (""+pos); 63 } 64 _pos = pos; 65 } 66 67 70 public Batch toFirst(){ 71 _pos = 0; 72 return this; 73 } 74 75 78 public Batch toLast(){ 79 _pos = _count - 1; 80 return this; 81 } 82 83 86 public Object getItemAt(int index){ 87 if(index < 0 || index >= _count){ 88 throw new java.lang.IndexOutOfBoundsException (""+index); 89 } 90 return _items[index]; 91 } 92 93 96 public boolean hasNext(){ 97 return _pos < _count; 98 } 99 100 103 public Object next(){ 104 if(_pos >= _count){ 105 throw new java.util.NoSuchElementException (); 106 } 107 if(_listener != null){ 108 try{ 109 Object next = (_items[_pos++]); 110 _listener.onNext(next); 111 return next; 112 }catch(Exception e){ 113 throw new CursorException("Error handing next object to cursor listener", e); 114 } 115 } 116 return _items[_pos++]; 117 } 118 119 122 public boolean hasPrevious(){ 123 return _pos > 0; 124 } 125 126 129 public Object previous(){ 130 if(_pos <= 0){ 131 throw new java.util.NoSuchElementException (); 132 } 133 return _items[_pos--]; 134 } 135 136 137 140 public java.util.Iterator getIterator(){ 141 return new BatchIterator(this, false); 142 } 143 144 147 public java.util.Iterator getReverseIterator(){ 148 return new BatchIterator(this, true); 149 } 150 151 153 public static class BatchIterator implements java.util.Iterator { 154 155 private Batch _batch; 156 private boolean _reverse; 157 158 BatchIterator(Batch batch, boolean reverse){ 159 _batch = batch; 160 _reverse = reverse; 161 } 162 163 public boolean hasNext(){ 164 if(_reverse){ 165 return _batch.hasPrevious(); 166 } 167 return _batch.hasNext(); 168 } 169 170 public Object next(){ 171 if(_reverse){ 172 return _batch.previous(); 173 } 174 return _batch.next(); 175 } 176 177 public void remove(){ 178 throw new UnsupportedOperationException (); 179 } 180 } 181 } 182 | Popular Tags |