001/*
002 * Copyright 2006-2007 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.support;
018
019import java.util.Iterator;
020
021import org.springframework.batch.item.ItemReader;
022import org.springframework.batch.item.ParseException;
023import org.springframework.batch.item.UnexpectedInputException;
024import org.springframework.util.Assert;
025
026/**
027 * An {@link ItemReader} that pulls data from a {@link Iterator} or
028 * {@link Iterable} using the constructors.
029 * 
030 * @author Juliusz Brzostek
031 * @author Dave Syer
032 */
033public class IteratorItemReader<T> implements ItemReader<T> {
034
035        /**
036         * Internal iterator
037         */
038        private final Iterator<T> iterator;
039
040        /**
041         * Construct a new reader from this iterable (could be a collection), by
042         * extracting an instance of {@link Iterator} from it.
043         * 
044         * @param iterable in instance of {@link Iterable}
045         * 
046         * @see Iterable#iterator()
047         */
048        public IteratorItemReader(Iterable<T> iterable) {
049                Assert.notNull(iterable, "Iterable argument cannot be null!");
050                this.iterator = iterable.iterator();
051        }
052
053        /**
054         * Construct a new reader from this iterator directly.
055         * @param iterator an instance of {@link Iterator}
056         */
057        public IteratorItemReader(Iterator<T> iterator) {
058                Assert.notNull(iterator, "Iterator argument cannot be null!");
059                this.iterator = iterator;
060        }
061
062        /**
063         * Implementation of {@link ItemReader#read()} that just iterates over the
064         * iterator provided.
065         */
066    @Override
067        public T read() {
068                if (iterator.hasNext())
069                        return iterator.next();
070                else
071                        return null; // end of data
072        }
073
074}