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.shared.ldap.model.cursor;
021
022
023import java.util.Iterator;
024
025import org.apache.directory.shared.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    public boolean hasNext()
068    {
069        return available;
070    }
071
072
073    /**
074     * {@inheritDoc}
075     */
076    public E next()
077    {
078        try
079        {
080            E element = cursor.get();
081            available = cursor.next();
082            return element;
083        }
084        catch ( Exception e )
085        {
086            throw new RuntimeException( I18n.err( I18n.ERR_02002_FAILURE_ON_UNDERLYING_CURSOR ), e );
087        }
088    }
089
090
091    /**
092     * {@inheritDoc}
093     */
094    public void remove()
095    {
096        throw new UnsupportedOperationException( I18n.err( I18n.ERR_02003_REMOVAL_NOT_SUPPORTED ) );
097    }
098}