1 | package org.springframework.batch.item.xml.stax; |
2 | |
3 | import java.util.NoSuchElementException; |
4 | |
5 | import javax.xml.stream.XMLEventReader; |
6 | import javax.xml.stream.XMLStreamException; |
7 | import javax.xml.stream.events.XMLEvent; |
8 | |
9 | import org.springframework.beans.factory.InitializingBean; |
10 | import org.springframework.util.Assert; |
11 | |
12 | /** |
13 | * Class used to wrap XMLEventReader. Events from wrapped reader are stored in |
14 | * {@link EventSequence} to support transactions. |
15 | * |
16 | * @author Tomas Slanina |
17 | * @author Robert Kasanicky |
18 | */ |
19 | public class DefaultTransactionalEventReader extends AbstractEventReaderWrapper implements TransactionalEventReader, InitializingBean { |
20 | |
21 | private EventSequence recorder = new EventSequence(); |
22 | |
23 | |
24 | /** |
25 | * Creates instance of this class and wraps XMLEventReader. |
26 | * |
27 | * @param wrappedReader event reader to be wrapped. |
28 | */ |
29 | public DefaultTransactionalEventReader(XMLEventReader wrappedReader) { |
30 | super(wrappedReader); |
31 | } |
32 | |
33 | public void afterPropertiesSet() throws Exception { |
34 | Assert.notNull(wrappedEventReader); |
35 | } |
36 | |
37 | /** |
38 | * Callback on transaction rollback. |
39 | */ |
40 | public void onRollback() { |
41 | recorder.reset(); |
42 | } |
43 | |
44 | /** |
45 | * Callback on transacion commit. |
46 | * |
47 | */ |
48 | public void onCommit() { |
49 | recorder.clear(); |
50 | } |
51 | |
52 | |
53 | /** |
54 | * Check if there are more events. Returns true if there are more events and |
55 | * false otherwise. |
56 | * |
57 | * @return true if the event reader has more events, false otherwise |
58 | */ |
59 | public boolean hasNext() { |
60 | return recorder.hasNext() || wrappedEventReader.hasNext(); |
61 | } |
62 | |
63 | /** |
64 | * Get the next XMLEvent |
65 | * |
66 | * @see XMLEvent |
67 | * @throws XMLStreamException if there is an error with the underlying XML. |
68 | * @throws NoSuchElementException iteration has no more elements. |
69 | */ |
70 | public XMLEvent nextEvent() throws XMLStreamException { |
71 | if (!recorder.hasNext()) { |
72 | recorder.addEvent(wrappedEventReader.nextEvent()); |
73 | } |
74 | return recorder.nextEvent(); |
75 | } |
76 | |
77 | /** |
78 | * Check the next XMLEvent without reading it from the stream. Returns null |
79 | * if the stream is at EOF or has no more XMLEvents. A call to peek() will |
80 | * be equal to the next return of next(). |
81 | * |
82 | * @see XMLEvent |
83 | * @throws XMLStreamException |
84 | */ |
85 | public XMLEvent peek() throws XMLStreamException { |
86 | return (recorder.hasNext()) ? recorder.peek() : wrappedEventReader.peek(); |
87 | } |
88 | |
89 | |
90 | /** |
91 | * In this implementation throws UnsupportedOperationException. |
92 | */ |
93 | public void remove() { |
94 | throw new UnsupportedOperationException(); |
95 | } |
96 | } |