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 | public synchronized Resource read() throws Exception { |
60 | int index = counter.incrementAndGet() - 1; |
61 | if (index >= resources.length) { |
62 | return null; |
63 | } |
64 | return resources[index]; |
65 | } |
66 | |
67 | public void close() throws ItemStreamException { |
68 | } |
69 | |
70 | public void open(ExecutionContext executionContext) throws ItemStreamException { |
71 | counter.set(executionContext.getInt(getKey("COUNT"), 0)); |
72 | } |
73 | |
74 | public void update(ExecutionContext executionContext) throws ItemStreamException { |
75 | executionContext.putInt(getKey("COUNT"), counter.get()); |
76 | } |
77 | |
78 | } |