package uk.gov.register.db;

import org.skife.jdbi.v2.ResultIterator;
import uk.gov.register.core.Entry;

public class EntryIteratorDAO {

    private final EntryQueryDAO entryDAO;
    private int nextValidEntryNumber;
    private ResultIterator<Entry> iterator;

    public EntryIteratorDAO(EntryQueryDAO entryDAO) {
        this.entryDAO = entryDAO;
        this.nextValidEntryNumber = -1;
    }

    public Entry findByEntryNumber(int entryNumber) {
        if (iterator == null || entryNumber != nextValidEntryNumber) {
            if (iterator != null) {
                iterator.close();
            }
            iterator = entryDAO.entriesIteratorFrom(entryNumber);
            nextValidEntryNumber = entryNumber;
        }
        nextValidEntryNumber++;
        return iterator.next();
    }
}

package uk.gov.register.db;

import org.skife.jdbi.v2.ResultIterator;
import uk.gov.register.core.Entry;

public class EntryIteratorDAO {

    private final EntryQueryDAO entryDAO;
    private int nextValidEntryNumber;
    private ResultIterator<Entry> iterator;

    public EntryIteratorDAO(EntryQueryDAO entryDAO) {
        this.entryDAO = entryDAO;
        this.nextValidEntryNumber = -1;
    }

    public Entry findByEntryNumber(int entryNumber) {
        if (iterator == null || !iterator.hasNext() || entryNumber != nextValidEntryNumber) {
            if (iterator != null) {
                iterator.close();
            }
            iterator = entryDAO.entriesIteratorFrom(entryNumber);
            nextValidEntryNumber = entryNumber;
        }
        nextValidEntryNumber++;
        return iterator.next();
    }
}

Check whether iterator is already closed
Check whether iterator is already closed

Sometimes the iterator may not be null but may be already closed. This
occurs because we have used the EntryIteratorDAO previously to read up to the end
of the iterator (which will close it). This now checks for the closed iterator and
recreates it if necessary.
