1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: BasicIterator.java,v 1.1 2008/02/07 17:12:26 mark Exp $ 7 */ 8 9package com.sleepycat.persist; 10 11import java.util.Iterator; 12import java.util.NoSuchElementException; 13 14import com.sleepycat.db.DatabaseException; 15import com.sleepycat.db.LockMode; 16import com.sleepycat.util.RuntimeExceptionWrapper; 17 18/** 19 * Implements Iterator for an arbitrary EntityCursor. 20 * 21 * @author Mark Hayes 22 */ 23class BasicIterator<V> implements Iterator<V> { 24 25 private EntityCursor<V> entityCursor; 26 private ForwardCursor<V> forwardCursor; 27 private LockMode lockMode; 28 private V nextValue; 29 30 /** 31 * An EntityCursor is given and the remove() method is supported. 32 */ 33 BasicIterator(EntityCursor<V> entityCursor, LockMode lockMode) { 34 this.entityCursor = entityCursor; 35 this.forwardCursor = entityCursor; 36 this.lockMode = lockMode; 37 } 38 39 /** 40 * A ForwardCursor is given and the remove() method is not supported. 41 */ 42 BasicIterator(ForwardCursor<V> forwardCursor, LockMode lockMode) { 43 this.forwardCursor = forwardCursor; 44 this.lockMode = lockMode; 45 } 46 47 public boolean hasNext() { 48 if (nextValue == null) { 49 try { 50 nextValue = forwardCursor.next(lockMode); 51 } catch (DatabaseException e) { 52 throw new RuntimeExceptionWrapper(e); 53 } 54 return nextValue != null; 55 } else { 56 return true; 57 } 58 } 59 60 public V next() { 61 if (hasNext()) { 62 V v = nextValue; 63 nextValue = null; 64 return v; 65 } else { 66 throw new NoSuchElementException(); 67 } 68 } 69 70 public void remove() { 71 if (entityCursor == null) { 72 throw new UnsupportedOperationException(); 73 } 74 try { 75 if (!entityCursor.delete()) { 76 throw new IllegalStateException 77 ("Record at cursor position is already deleted"); 78 } 79 } catch (DatabaseException e) { 80 throw new RuntimeExceptionWrapper(e); 81 } 82 } 83} 84