|
39 | 39 | */ |
40 | 40 | package org.javaee7.batch.chunk.exception; |
41 | 41 |
|
42 | | -import java.io.Serializable; |
43 | | -import java.util.StringTokenizer; |
44 | 42 | import javax.batch.api.chunk.AbstractItemReader; |
45 | 43 | import javax.inject.Named; |
| 44 | +import java.io.Serializable; |
| 45 | +import java.util.StringTokenizer; |
46 | 46 |
|
47 | 47 | /** |
48 | 48 | * @author Arun Gupta |
49 | 49 | */ |
50 | 50 | @Named |
51 | 51 | public class MyItemReader extends AbstractItemReader { |
52 | | - |
| 52 | + |
53 | 53 | private StringTokenizer tokens; |
54 | | - |
| 54 | + |
| 55 | + private MyInputRecord lastElement; |
| 56 | + private boolean alreadyFailed; |
| 57 | + |
55 | 58 | @Override |
56 | | - public void open(Serializable c) { |
| 59 | + public void open(Serializable checkpoint) { |
57 | 60 | tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ","); |
| 61 | + |
| 62 | + // This will place the nextToken into the last batch checkpoint. Called on exception retry. |
| 63 | + if (checkpoint != null) { |
| 64 | + while (!Integer.valueOf(tokens.nextToken()).equals(((MyInputRecord) checkpoint).getId())) { |
| 65 | + System.out.println("Skipping already read elements"); |
| 66 | + } |
| 67 | + } |
58 | 68 | } |
59 | | - |
| 69 | + |
60 | 70 | @Override |
61 | 71 | public Object readItem() { |
62 | 72 | if (tokens.hasMoreTokens()) { |
63 | 73 | int token = Integer.valueOf(tokens.nextToken()); |
64 | | - if (token == 3) |
65 | | - throw new IllegalArgumentException(); |
66 | | - |
67 | | - return new MyInputRecord(token); |
| 74 | + |
| 75 | + // Simulate a read exception when the token is equal to 5. Do it once only. |
| 76 | + if (token == 5 && !alreadyFailed) { |
| 77 | + alreadyFailed = true; |
| 78 | + throw new IllegalArgumentException("Could not read record"); |
| 79 | + } |
| 80 | + |
| 81 | + lastElement = new MyInputRecord(token); |
| 82 | + System.out.println("MyItemReader.readItem " + lastElement); |
| 83 | + return lastElement; |
68 | 84 | } |
69 | 85 | return null; |
70 | 86 | } |
| 87 | + |
| 88 | + @Override |
| 89 | + public Serializable checkpointInfo() throws Exception { |
| 90 | + // This is used internally by batch to stop the retry. Remember to implement equals on the read elements. |
| 91 | + return lastElement; |
| 92 | + } |
71 | 93 | } |
0 commit comments