1 package org.apache.maven.shared.utils.cli;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.PrintWriter;
27 import java.io.Reader;
28 import java.nio.charset.Charset;
29
30 import javax.annotation.Nullable;
31
32 import org.apache.maven.shared.utils.io.IOUtil;
33
34
35
36
37
38
39
40 public class StreamPumper
41 extends AbstractStreamHandler
42 {
43 private final BufferedReader in;
44
45 private final StreamConsumer consumer;
46
47 private final PrintWriter out;
48
49 private volatile Exception exception = null;
50
51 private static final int SIZE = 1024;
52
53
54
55
56
57 public StreamPumper( InputStream in, StreamConsumer consumer )
58 {
59 this( new InputStreamReader( in ), null, consumer );
60 }
61
62
63
64
65
66
67 public StreamPumper( InputStream in, StreamConsumer consumer, @Nullable Charset charset )
68 {
69 this( null == charset ? new InputStreamReader( in ) : new InputStreamReader( in, charset ), null, consumer );
70 }
71
72
73
74
75
76
77 private StreamPumper( Reader in, PrintWriter writer, StreamConsumer consumer )
78 {
79 this.in = new BufferedReader( in, SIZE );
80 this.out = writer;
81 this.consumer = consumer;
82 }
83
84
85 public void run()
86 {
87 try
88 {
89 for ( String line = in.readLine(); line != null; line = in.readLine() )
90 {
91 try
92 {
93 if ( exception == null )
94 {
95 consumeLine( line );
96 }
97 }
98 catch ( Exception t )
99 {
100 exception = t;
101 }
102
103 if ( out != null )
104 {
105 out.println( line );
106
107 out.flush();
108 }
109
110 }
111 }
112 catch ( IOException e )
113 {
114 exception = e;
115 }
116 finally
117 {
118 IOUtil.close( in );
119
120 synchronized ( this )
121 {
122 setDone();
123
124 this.notifyAll();
125 }
126 }
127 }
128
129
130
131
132 public void flush()
133 {
134 if ( out != null )
135 {
136 out.flush();
137 }
138 }
139
140
141
142
143 public void close()
144 {
145 IOUtil.close( out );
146 }
147
148
149
150
151 public Exception getException()
152 {
153 return exception;
154 }
155
156 private void consumeLine( String line )
157 {
158 if ( consumer != null && !isDisabled() )
159 {
160 consumer.consumeLine( line );
161 }
162 }
163 }