Debian Codegraph @

src/main/java/org/freehep/util/io/RoutedInputStream.java

raw
1 // Copyright 2002, FreeHEP.
2 package org.freehep.util.io;
3
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.Map;
9
10 /**
11 * The RoutedInputStream allows the user to add a listener for a certain
12 * delimited portion of the main inputstream. This portion is marked by a start
13 * and end marker. The end marker can be null, in which case the portion runs
14 * from the start marker to the end of the main inputstream. The listener is
15 * informed via a route (partial inputstream) when input is available. The new
16 * routed inputstream (route) is supposed to be read to the end or closed, after
17 * which the main inputstream should be read again. Closing a route will not
18 * close the original stream, but will discard any bytes up to and including the
19 * end marker. Returning from a route without reading until the end of the route
20 * means that the remaining bytes are still available on the main stream.
21 * Multiple routes can be added, as long as they have different start sequences.
22 * Start sequences such as "StartA, StartB, StartEmpty" are allowed, but "Start,
23 * StartOther" are not since they overlap. Start and End markers can be the
24 * same.
25 *
26 * IMPORTANT: inherits from InputStream rather than FilterInputStream so that
27 * the correct read(byte[], int, int) method is used.
28 *
29 * @author Mark Donszelmann
30 * @version $Id: RoutedInputStream.java 8584 2006-08-10 23:06:37Z duns $
31 */
32 public class RoutedInputStream extends InputStream {
33
34 private InputStream in;
35
36 private Map routes, listeners;
37
38 private byte[] buffer;
39
40 private int sob, eob;
41
42 private int index;
43
44 private int state;
45
46 private byte[] start;
47
48 private static final int UNROUTED = 0; // the main stream is returned
49
50 private static final int ROUTEFOUND = 1; // found a route, but need to
51 // still return buffer
52
53 private static final int ROUTEINFORM = 2; // buffer returned, need to
54 // inform routelistener
55
56 private static final int ROUTED = 3; // the main stream is now routed to
57 // the route
58
59 private static final int CLOSING = 4; // the underlying stream is closed,
60 // but buffer need to be emptied
61
62 private static final int CLOSED = 5; // the main stream is closed
63
64 /**
65 * Creates a RoutedInputStream from the underlying stream.
66 *
67 * @param input stream to read
68 */
69 public RoutedInputStream(InputStream input) {
70 super();
71 in = input;
72 routes = new HashMap();
73 listeners = new HashMap();
74 // bufferlength has to be more than 1
75 buffer = new byte[20];
76 sob = -1;
77 eob = 0;
78 index = 0;
79 state = UNROUTED;
80 }
81
82 /**
83 * Returns the next byte on this stream, however if a start marker is found,
84 * the associated route listener is called, which should take over reading
85 * the stream. In this case this method will, after the route is finished
86 * reading and closed, return the first byte after the end marker. This of
87 * course unless that byte is part of the next start marker.
88 */
89 public int read() throws IOException {
90
91 int result;
92
93 NEWSTATE: while (true) {
94 switch (state) {
95 default:
96 case UNROUTED:
97 // fill the buffer with one or more bytes
98 int b = -1;
99 while (sob != eob) {
100 if (sob < 0)
101 sob = 0;
102
103 // read a byte from the underlying stream
104 b = in.read();
105 if (b < 0) {
106 // underlying stream closed
107 state = CLOSING;
108 continue NEWSTATE;
109 }
110
111 // try to find a start marker
112 buffer[eob] = (byte) b;
113 eob = (eob + 1) % buffer.length;
114
115 // search for a route
116 for (Iterator i = routes.keySet().iterator(); i.hasNext();) {
117 start = (byte[]) i.next();
118 index = (eob + buffer.length - start.length)
119 % buffer.length;
120 if (equals(start, buffer, index)) {
121 state = ROUTEFOUND;
122 continue NEWSTATE;
123 }
124 }
125
126 } // while
127
128 // always return what drops from the buffer
129 // the buffer is one byte longer than the longest start marker,
130 // so even
131 // if we find that marker we can still return the byte just in
132 // front of it.
133 result = buffer[sob];
134 sob = (sob + 1) % buffer.length;
135 return result;
136
137 case ROUTEFOUND:
138 // found a start marker, we still need to return all bytes
139 // before
140 // the marker; i.e. from sob to index
141 if (sob == index) {
142 state = ROUTEINFORM;
143 continue NEWSTATE;
144 }
145 result = buffer[sob];
146 sob = (sob + 1) % buffer.length;
147 return result;
148
149 case ROUTEINFORM:
150 // we inform the routelistener to start reading
151 state = ROUTED;
152 Route route = new Route(start, (byte[]) routes.get(start));
153 // next call will generate callbacks to this read method in
154 // state ROUTED.
155 ((RouteListener) listeners.get(start)).routeFound(route);
156
157 // route listener finished
158 state = UNROUTED;
159 if (sob == eob) {
160 // we restart buffering if the buffer was empty
161 sob = -1;
162 eob = 0;
163 continue NEWSTATE;
164 }
165 // FIXME: we need an UNROUTING here which just returns the
166 // buffer, but does not refill it, in case the reads would
167 // block...
168 // we return a byte from the buffer and
169 // let the next call take care of rebuffering, otherwise we may
170 // block
171 result = buffer[sob];
172 sob = (sob + 1) % buffer.length;
173 return result;
174
175 case ROUTED:
176 // calls end up here when the Route is reading. We should
177 // return the start marker (in buffer) followed by newly read
178 // bytes.
179 if (sob == eob) {
180 result = in.read();
181 if (result < 0) {
182 state = CLOSED;
183 continue NEWSTATE;
184 }
185 } else {
186 result = buffer[sob];
187 sob = (sob + 1) % buffer.length;
188 }
189 return result;
190
191 case CLOSING:
192 // the underlying stream is closed, no more markers can be found
193 // thus the rest of the buffer is returned
194 if (sob == eob) {
195 state = CLOSED;
196 continue NEWSTATE;
197 }
198 result = buffer[sob];
199 sob = (sob + 1) % buffer.length;
200 return result;
201
202 case CLOSED:
203 // all streams are closed
204 return -1;
205 } // switch
206 } // while
207 }
208
209 /**
210 * Adds a route for given start and end string. The strings are converted
211 * according to the default encoding to start and end markers (byte[]).
212 *
213 * @param start start marker
214 * @param end end marker
215 * @param listener listener to inform about the route
216 */
217 public void addRoute(String start, String end, RouteListener listener) {
218 addRoute(start.getBytes(), (end == null) ? null : end.getBytes(),
219 listener);
220 }
221
222 /**
223 * Adds a route for given start and end marker.
224 *
225 * If the end marker is null, the route is indefinite, and can be read until
226 * the main stream ends.
227 *
228 * If the start and end marker are equal, the route can be read for exactly
229 * their length.
230 *
231 * @param start start marker
232 * @param end end marker
233 * @param listener listener to inform about the route
234 */
235 public void addRoute(byte[] start, byte[] end, RouteListener listener) {
236 for (Iterator i = routes.keySet().iterator(); i.hasNext();) {
237 String key = new String((byte[]) i.next());
238 String name = new String(start);
239 if (key.startsWith(name) || name.startsWith(key)) {
240 throw new IllegalArgumentException("Route '" + name
241 + "' cannot be added since it overlaps with '" + key
242 + "'.");
243 }
244 }
245
246 routes.put(start, end);
247 listeners.put(start, listener);
248 // we make the buffer one longer than the longest start marker, so that
249 // read() can always return a byte before a marker.
250 if (start.length > buffer.length - 1) {
251 byte[] tmp = new byte[start.length + 1];
252 System.arraycopy(buffer, 0, tmp, 0, buffer.length);
253 buffer = tmp;
254 }
255 }
256
257 /**
258 * Checks if cmp is equal to buf (with start at index) for the length of
259 * cmp.
260 *
261 * @param cmp buffer1 to compare
262 * @param buf buffer2 to compare
263 * @param index start index to start compare
264 * @return true if cmp == buf for length of cmp.
265 */
266 private static boolean equals(byte[] cmp, byte[] buf, int index) {
267 for (int i = cmp.length - 1; i > 0; i--) {
268 int j = (index + buf.length + i) % buf.length;
269 if (buf[j] != cmp[i]) {
270 return false;
271 }
272 }
273
274 return buf[(index + buf.length) % buf.length] == cmp[0];
275 }
276
277 /**
278 * Route which can be read up to and including the end marker.
279 *
280 * When you close the route, all bytes including the end marker will be
281 * read/discarded before returning.
282 *
283 * If you just discard the Route, the underlying stream will still return
284 * you all or part of the bytes of this route.
285 *
286 * If the end marker is set to null, the stream can be read until the
287 * underlying stream ends.
288 */
289 public class Route extends InputStream {
290
291 private byte[] start, end;
292
293 private byte[] buffer;
294
295 private int index;
296
297 private boolean closed;
298
299 /**
300 * Creates a route with given start and end marker.
301 *
302 * @param start start marker
303 * @param end end marker
304 */
305 public Route(byte[] start, byte[] end) {
306 this.start = start;
307 this.end = end;
308 if (end != null)
309 buffer = new byte[end.length];
310 index = 0;
311 closed = false;
312 }
313
314 /**
315 * Returns bytes of this specific route, starting with the start marker,
316 * followed by any bytes up to and including the end marker.
317 *
318 * If the end marker is null, the route is indefinite.
319 */
320 public int read() throws IOException {
321 if (closed)
322 return -1;
323
324 int b = RoutedInputStream.this.read();
325 if (b < 0) {
326 closed = true;
327 return b;
328 }
329
330 if (end == null)
331 return b;
332
333 buffer[index] = (byte) b;
334 index = (index + 1) % buffer.length;
335
336 closed = RoutedInputStream.equals(end, buffer, index);
337
338 return b;
339 }
340
341 /**
342 * Closes the stream, and discards any bytes up to and including the end
343 * marker.
344 */
345 public void close() throws IOException {
346 while (read() >= 0) {
347 }
348 ;
349 closed = true;
350 }
351
352 /**
353 * Returns start marker.
354 *
355 * @return start marker
356 */
357 public byte[] getStart() {
358 return start;
359 }
360
361 /**
362 * Returns end marker.
363 *
364 * @return end marker
365 */
366 public byte[] getEnd() {
367 return end;
368 }
369 }
370 }