1 package ca.uhn.hl7v2.util;
2
3 import java.io.InputStream;
4 import java.io.Reader;
5 import java.util.Iterator;
6
7 import ca.uhn.hl7v2.DefaultHapiContext;
8 import ca.uhn.hl7v2.HL7Exception;
9 import ca.uhn.hl7v2.HapiContext;
10 import ca.uhn.hl7v2.HapiContextSupport;
11 import ca.uhn.hl7v2.model.Message;
12 import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
13 import ca.uhn.hl7v2.util.Hl7InputStreamMessageStringIterator.ParseFailureError;
14 import ca.uhn.hl7v2.validation.impl.ValidationContextFactory;
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 public class Hl7InputStreamMessageIterator extends HapiContextSupport implements Iterator<Message> {
38
39 private Class<? extends Message> myMessageType;
40 private final Hl7InputStreamMessageStringIterator myWrapped;
41
42
43
44
45
46
47
48 public Hl7InputStreamMessageIterator(InputStream theInputStream) {
49 this(theInputStream, new DefaultHapiContext(ValidationContextFactory.noValidation()));
50 }
51
52
53
54
55
56
57
58 public Hl7InputStreamMessageIterator(Reader theReader) {
59 this(theReader, new DefaultHapiContext(ValidationContextFactory.noValidation()));
60 }
61
62
63
64
65
66
67
68
69
70 public Hl7InputStreamMessageIterator(InputStream theInputStream, HapiContext theHapiContext) {
71 super(theHapiContext);
72 myWrapped = new Hl7InputStreamMessageStringIterator(theInputStream);
73 }
74
75
76
77
78
79
80
81
82
83 public Hl7InputStreamMessageIterator(Reader theReader, HapiContext theHapiContext) {
84 super(theHapiContext);
85 myWrapped = new Hl7InputStreamMessageStringIterator(theReader);
86 }
87
88
89
90
91
92 public static Hl7InputStreamMessageIterator getForClasspathResource(String theClasspath) {
93 InputStream is = Hl7InputStreamMessageIterator.class.getResourceAsStream(theClasspath);
94 if (is == null) {
95 throw new IllegalArgumentException("Can't find resource: " + theClasspath);
96 }
97 return new Hl7InputStreamMessageIterator(is);
98 }
99
100
101
102
103 public boolean hasNext() {
104 return myWrapped.hasNext();
105 }
106
107
108
109
110 public Message next() {
111 String nextString = myWrapped.next();
112 Message retVal;
113 try {
114 if (myMessageType != null) {
115 retVal = ReflectionUtil.instantiateMessage(myMessageType, getHapiContext().getModelClassFactory());
116 retVal.parse(nextString);
117 } else {
118 retVal = getHapiContext().getPipeParser().parse(nextString);
119 }
120 } catch (HL7Exception e) {
121 throw new ParseFailureError("Failed to parse message", e);
122 }
123 return retVal;
124 }
125
126
127
128
129
130
131
132 public void remove() {
133 throw new UnsupportedOperationException();
134 }
135
136
137
138
139
140 public void setIgnoreComments(boolean theIgnoreComments) {
141 myWrapped.setIgnoreComments(theIgnoreComments);
142 }
143
144
145
146
147
148 public void setMessageType(Class<? extends Message> theMessageType) {
149 myMessageType = theMessageType;
150 }
151
152 }