View Javadoc

1   package org.springframework.batch.item.file;
2   
3   import java.util.Arrays;
4   import java.util.concurrent.atomic.AtomicInteger;
5   
6   import org.springframework.batch.item.ExecutionContext;
7   import org.springframework.batch.item.ItemReader;
8   import org.springframework.batch.item.ItemStreamException;
9   import org.springframework.batch.item.ItemStreamReader;
10  import org.springframework.batch.item.util.ExecutionContextUserSupport;
11  import org.springframework.core.io.Resource;
12  import org.springframework.core.io.support.ResourceArrayPropertyEditor;
13  
14  /**
15   * {@link ItemReader} which produces {@link Resource} instances from an array.
16   * This can be used conveniently with a configuration entry that injects a
17   * pattern (e.g. <code>mydir/*.txt</code>, which can then be converted by Spring
18   * to an array of Resources by the ApplicationContext.
19   * 
20   * <br/>
21   * <br/>
22   * 
23   * Thread safe between calls to {@link #open(ExecutionContext)}. The
24   * {@link ExecutionContext} is not accurate in a multi-threaded environment, so
25   * do not rely on that data for restart (i.e. always open with a fresh context).
26   * 
27   * @author Dave Syer
28   * 
29   * @see ResourceArrayPropertyEditor
30   * 
31   * @since 2.1
32   */
33  public class ResourcesItemReader extends ExecutionContextUserSupport implements ItemStreamReader<Resource> {
34  
35  	private Resource[] resources = new Resource[0];
36  
37  	private AtomicInteger counter = new AtomicInteger(0);
38  
39  	{
40  		/*
41  		 * Initialize the name for the key in the execution context.
42  		 */
43  		setName(getClass().getName());
44  	}
45  
46  	/**
47  	 * The resources to serve up as items. Hint: use a pattern to configure.
48  	 * 
49  	 * @param resources the resources
50  	 */
51  	public void setResources(Resource[] resources) {
52  		this.resources = Arrays.asList(resources).toArray(new Resource[resources.length]);
53  	}
54  
55  	/**
56  	 * Increments a counter and returns the next {@link Resource} instance from
57  	 * the input, or null if none remain.
58  	 */
59      @Override
60  	public synchronized Resource read() throws Exception {
61  		int index = counter.incrementAndGet() - 1;
62  		if (index >= resources.length) {
63  			return null;
64  		}
65  		return resources[index];
66  	}
67  
68      @Override
69  	public void close() throws ItemStreamException {
70  	}
71  
72      @Override
73  	public void open(ExecutionContext executionContext) throws ItemStreamException {
74  		counter.set(executionContext.getInt(getKey("COUNT"), 0));
75  	}
76  
77      @Override
78  	public void update(ExecutionContext executionContext) throws ItemStreamException {
79  		executionContext.putInt(getKey("COUNT"), counter.get());
80  	}
81  
82  }