1 package org.apache.maven.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25
26
27 /**
28 * A class to asynchronously read the provided InputStream and
29 * provide the output as a String
30 *
31 * @author <a href="mailto:dion@multitask.com.au">dIon Gillard</a>
32 * @version $Id: AsyncStreamReader.java 532339 2007-04-25 12:28:56Z ltheussl $
33 */
34 public class AsyncStreamReader extends Thread
35 {
36 /** buffer to dump output to */
37 private StringBuffer streamBuffer = new StringBuffer();
38
39 /** stream to read from */
40 private BufferedReader stream;
41
42 /**
43 * Create a reader to process the provided stream
44 * @param anInputStream any input stream
45 */
46 public AsyncStreamReader( InputStream anInputStream )
47 {
48 if ( anInputStream == null )
49 {
50 throw new NullPointerException( "input stream parameter is null" );
51 }
52
53 stream = new BufferedReader( new InputStreamReader( anInputStream ) );
54 }
55
56 /**
57 * Read lines from the input stream provided, appending to a buffer
58 * for retrieval via the toString() method
59 */
60 public void run()
61 {
62 String line;
63
64 try
65 {
66 while ( ( line = stream.readLine() ) != null )
67 {
68 if ( okToConsume( line ) )
69 {
70 streamBuffer.append( line );
71 streamBuffer.append( '\n' );
72 }
73 }
74 }
75 catch ( IOException ioe )
76 {
77 ioe.printStackTrace();
78 }
79 }
80
81 /**
82 * @return the contents of the buffer
83 */
84 public String toString()
85 {
86 return streamBuffer.toString();
87 }
88
89 /**
90 * Indicate if its ok to consume (add to the buffer) this line. This
91 * implementation always returns <code>true</code>.
92 *
93 * @param line the line to check.
94 * @return if its ok to add this line to the buffer.
95 */
96 protected boolean okToConsume( String line )
97 {
98 return true;
99 }
100 }
101