1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util.stream;
17
18 import java.io.BufferedReader;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.PrintWriter;
23
24 import org.codehaus.plexus.util.IOUtil;
25 import org.codehaus.plexus.util.cli.AbstractStreamHandler;
26 import org.codehaus.plexus.util.cli.StreamConsumer;
27
28
29
30
31
32
33 public class StreamPumper extends AbstractStreamHandler {
34
35 private final BufferedReader in;
36 private final StreamConsumer consumer;
37 private final PrintWriter out;
38 private volatile Exception exception = null;
39 private static final int SIZE = 1024;
40
41 public StreamPumper(InputStream in) {
42 this(in, (StreamConsumer) null);
43 }
44
45 public StreamPumper(InputStream in, StreamConsumer consumer) {
46 this(in, (PrintWriter) null, consumer);
47 }
48
49 public StreamPumper(InputStream in, PrintWriter writer) {
50 this(in, writer, null);
51 }
52
53 public StreamPumper(InputStream in, PrintWriter writer, StreamConsumer consumer) {
54 this(new BufferedReader(new InputStreamReader(in), SIZE), writer, consumer);
55 }
56
57 public StreamPumper(InputStream in, String encoding, StreamConsumer consumer) throws IOException {
58 this(new BufferedReader(new InputStreamReader(in, encoding), SIZE), null, consumer);
59 }
60
61 public StreamPumper(BufferedReader in, PrintWriter writer, StreamConsumer consumer) {
62 this.in = in;
63 this.out = writer;
64 this.consumer = consumer;
65 }
66
67 @Override
68 public void run() {
69 try {
70 for (String line = in.readLine(); line != null; line = in.readLine()) {
71 try {
72 if (exception == null) {
73 consumeLine(line);
74 }
75 } catch (Exception t) {
76 exception = t;
77 }
78
79 if (out != null) {
80 out.println(line);
81 out.flush();
82 }
83 }
84 } catch (IOException e) {
85 exception = e;
86 } finally {
87 IOUtil.close(in);
88 synchronized (this) {
89 setDone();
90 this.notifyAll();
91 }
92 }
93 }
94
95 public void flush() {
96 if (out != null) {
97 out.flush();
98 }
99 }
100
101 public void close() {
102 IOUtil.close(out);
103 }
104
105 public Exception getException() {
106 return exception;
107 }
108
109 private void consumeLine(String line) {
110 if (consumer != null && !isDisabled()) {
111 consumer.consumeLine(line);
112 }
113 }
114 }