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
41
42 public class StreamPumper
43 extends AbstractStreamHandler
44 {
45 private final BufferedReader in;
46
47 private final StreamConsumer consumer;
48
49 private final PrintWriter out;
50
51 private volatile Exception exception = null;
52
53 private static final int SIZE = 1024;
54
55 public StreamPumper( InputStream in, StreamConsumer consumer )
56 {
57 this( new InputStreamReader( in ), null, consumer );
58 }
59
60 public StreamPumper( InputStream in, StreamConsumer consumer, @Nullable Charset charset )
61 {
62 this( null == charset ? new InputStreamReader( in ) : new InputStreamReader( in, charset ), null, consumer );
63 }
64
65 private StreamPumper( Reader in, PrintWriter writer, StreamConsumer consumer )
66 {
67 this.in = new BufferedReader( in, SIZE );
68 this.out = writer;
69 this.consumer = consumer;
70 }
71
72 public void run()
73 {
74 try
75 {
76 for ( String line = in.readLine(); line != null; line = in.readLine() )
77 {
78 try
79 {
80 if ( exception == null )
81 {
82 consumeLine( line );
83 }
84 }
85 catch ( Exception t )
86 {
87 exception = t;
88 }
89
90 if ( out != null )
91 {
92 out.println( line );
93
94 out.flush();
95 }
96
97 }
98 }
99 catch ( IOException e )
100 {
101 exception = e;
102 }
103 finally
104 {
105 IOUtil.close( in );
106
107 synchronized ( this )
108 {
109 setDone();
110
111 this.notifyAll();
112 }
113 }
114 }
115
116 public void flush()
117 {
118 if ( out != null )
119 {
120 out.flush();
121 }
122 }
123
124 public void close()
125 {
126 IOUtil.close( out );
127 }
128
129 public Exception getException()
130 {
131 return exception;
132 }
133
134 private void consumeLine( String line )
135 {
136 if ( consumer != null && !isDisabled() )
137 {
138 consumer.consumeLine( line );
139 }
140 }
141 }