1 /*
2 * Copyright 2006-2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.springframework.batch.item.support;
18
19 import java.util.Iterator;
20
21 import org.springframework.batch.item.ItemReader;
22 import org.springframework.batch.item.ParseException;
23 import org.springframework.batch.item.UnexpectedInputException;
24 import org.springframework.util.Assert;
25
26 /**
27 * An {@link ItemReader} that pulls data from a {@link Iterator} or
28 * {@link Iterable} using the constructors.
29 *
30 * @author Juliusz Brzostek
31 * @author Dave Syer
32 */
33 public class IteratorItemReader<T> implements ItemReader<T> {
34
35 /**
36 * Internal iterator
37 */
38 private final Iterator<T> iterator;
39
40 /**
41 * Construct a new reader from this iterable (could be a collection), by
42 * extracting an instance of {@link Iterator} from it.
43 *
44 * @param iterable in instance of {@link Iterable}
45 *
46 * @see Iterable#iterator()
47 */
48 public IteratorItemReader(Iterable<T> iterable) {
49 Assert.notNull(iterable, "Iterable argument cannot be null!");
50 this.iterator = iterable.iterator();
51 }
52
53 /**
54 * Construct a new reader from this iterator directly.
55 * @param iterator an instance of {@link Iterator}
56 */
57 public IteratorItemReader(Iterator<T> iterator) {
58 Assert.notNull(iterator, "Iterator argument cannot be null!");
59 this.iterator = iterator;
60 }
61
62 /**
63 * Implementation of {@link ItemReader#read()} that just iterates over the
64 * iterator provided.
65 */
66 @Override
67 public T read() throws Exception, UnexpectedInputException, ParseException {
68 if (iterator.hasNext())
69 return iterator.next();
70 else
71 return null; // end of data
72 }
73
74 }