01: package abbot.util;
02:
03: import java.io.BufferedInputStream;
04: import java.io.IOException;
05: import java.io.InputStream;
06:
07: import abbot.Log;
08:
09: /** Handle process output. */
10:
11: public class InputStreamHandler extends Thread {
12: private InputStream stream = null;
13:
14: public InputStreamHandler(InputStream stream) {
15: super ("Process Input Stream Handler");
16: setDaemon(true);
17: this .stream = new BufferedInputStream(stream);
18: }
19:
20: /** Override this method to do something meaningful with the output. */
21: public void handleBytes(byte[] buf, int count) {
22: }
23:
24: // WARNING: closing a process output stream prematurely may result in
25: // the Process object never detecting its termination!
26: private void close() {
27: try {
28: stream.close();
29: } catch (IOException io) {
30: Log.debug(io);
31: }
32: }
33:
34: public void run() {
35: int BUFSIZE = 256;
36: byte[] buf = new byte[BUFSIZE];
37: Log.debug("Stream reader started");
38: while (true) {
39: try {
40: Log.debug("Reading from stream");
41: int count = stream.read(buf, 0, buf.length);
42: if (count == -1) {
43: Log.debug("end of stream");
44: break;
45: } else if (count == 0) {
46: Log.debug("No input, sleeping");
47: try {
48: sleep(100);
49: } catch (InterruptedException e) {
50: Log.debug(e);
51: }
52: } else if (count > 0) {
53: Log.debug("Got " + count + " bytes");
54: handleBytes(buf, count);
55: }
56: } catch (IOException io) {
57: // we'll get this when the stream closes
58: Log.debug(io);
59: break;
60: }
61: }
62: close();
63: Log.debug("stream handler terminating");
64: }
65: }
|