001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.directory.api.ldap.model.cursor; 021 022 023import java.util.Iterator; 024 025import org.apache.directory.api.i18n.I18n; 026 027 028/** 029 * An Iterator over a Cursor so Cursors can be Iterable for using in foreach 030 * constructs. 031 * 032 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> 033 * @param <E> The type of element on which this cursor will iterate 034 */ 035public class CursorIterator<E> implements Iterator<E> 036{ 037 /** The inner cursor we will iterate */ 038 private final Cursor<E> cursor; 039 040 /** A flag used to store the cursor state */ 041 private boolean available; 042 043 044 /** 045 * Creates a new instance of CursorIterator. 046 * 047 * @param cursor The inner cursor 048 */ 049 public CursorIterator( Cursor<E> cursor ) 050 { 051 this.cursor = cursor; 052 053 try 054 { 055 this.available = cursor.next(); 056 } 057 catch ( Exception e ) 058 { 059 this.available = false; 060 } 061 } 062 063 064 /** 065 * {@inheritDoc} 066 */ 067 @Override 068 public boolean hasNext() 069 { 070 return available; 071 } 072 073 074 /** 075 * {@inheritDoc} 076 */ 077 @Override 078 public E next() 079 { 080 try 081 { 082 E element = cursor.get(); 083 available = cursor.next(); 084 085 return element; 086 } 087 catch ( Exception e ) 088 { 089 throw new RuntimeException( I18n.err( I18n.ERR_02002_FAILURE_ON_UNDERLYING_CURSOR ), e ); 090 } 091 } 092 093 094 /** 095 * {@inheritDoc} 096 */ 097 @Override 098 public void remove() 099 { 100 throw new UnsupportedOperationException( I18n.err( I18n.ERR_02003_REMOVAL_NOT_SUPPORTED ) ); 101 } 102}