1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 * 19 */ 20 package org.apache.directory.api.ldap.model.cursor; 21 22 23 import java.util.Iterator; 24 25 import org.apache.directory.api.i18n.I18n; 26 27 28 /** 29 * An Iterator over a Cursor so Cursors can be Iterable for using in foreach 30 * constructs. 31 * 32 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> 33 * @param <E> The type of element on which this cursor will iterate 34 */ 35 public class CursorIterator<E> implements Iterator<E> 36 { 37 /** The inner cursor we will iterate */ 38 private final Cursor<E> cursor; 39 40 /** A flag used to store the cursor state */ 41 private boolean available; 42 43 44 /** 45 * Creates a new instance of CursorIterator. 46 * 47 * @param cursor The inner cursor 48 */ 49 public CursorIterator( Cursor<E> cursor ) 50 { 51 this.cursor = cursor; 52 53 try 54 { 55 this.available = cursor.next(); 56 } 57 catch ( Exception e ) 58 { 59 this.available = false; 60 } 61 } 62 63 64 /** 65 * {@inheritDoc} 66 */ 67 @Override 68 public boolean hasNext() 69 { 70 return available; 71 } 72 73 74 /** 75 * {@inheritDoc} 76 */ 77 @Override 78 public E next() 79 { 80 try 81 { 82 E element = cursor.get(); 83 available = cursor.next(); 84 85 return element; 86 } 87 catch ( Exception e ) 88 { 89 throw new RuntimeException( I18n.err( I18n.ERR_02002_FAILURE_ON_UNDERLYING_CURSOR ), e ); 90 } 91 } 92 93 94 /** 95 * {@inheritDoc} 96 */ 97 @Override 98 public void remove() 99 { 100 throw new UnsupportedOperationException( I18n.err( I18n.ERR_02003_REMOVAL_NOT_SUPPORTED ) ); 101 } 102 }