1 package org.apache.maven.shared.utils.cli;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
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 org.apache.maven.shared.utils.io.IOUtil;
28
29 /**
30 * Class to pump the error stream during Process's runtime. Copied from the Ant
31 * built-in task.
32 *
33 * @author <a href="mailto:fvancea@maxiq.com">Florin Vancea </a>
34 * @author <a href="mailto:pj@thoughtworks.com">Paul Julius </a>
35 *
36 */
37 public class StreamPumper
38 extends AbstractStreamHandler
39 {
40 private final BufferedReader in;
41
42 private final StreamConsumer consumer;
43
44 private final PrintWriter out;
45
46 private volatile Exception exception = null;
47
48 private static final int SIZE = 1024;
49
50 public StreamPumper( InputStream in, StreamConsumer consumer )
51 {
52 this( in, null, consumer );
53 }
54
55 private StreamPumper( InputStream in, PrintWriter writer, StreamConsumer consumer )
56 {
57 this.in = new BufferedReader( new InputStreamReader( in ), SIZE );
58 this.out = writer;
59 this.consumer = consumer;
60 }
61
62 public void run()
63 {
64 try
65 {
66 for ( String line = in.readLine(); line != null; line = in.readLine() )
67 {
68 try
69 {
70 if ( exception == null )
71 {
72 consumeLine( line );
73 }
74 }
75 catch ( Exception t )
76 {
77 exception = t;
78 }
79
80 if ( out != null )
81 {
82 out.println( line );
83
84 out.flush();
85 }
86
87 }
88 }
89 catch ( IOException e )
90 {
91 exception = e;
92 }
93 finally
94 {
95 IOUtil.close( in );
96
97 synchronized ( this )
98 {
99 setDone();
100
101 this.notifyAll();
102 }
103 }
104 }
105
106 public void flush()
107 {
108 if ( out != null )
109 {
110 out.flush();
111 }
112 }
113
114 public void close()
115 {
116 IOUtil.close( out );
117 }
118
119 public Exception getException()
120 {
121 return exception;
122 }
123
124 private void consumeLine( String line )
125 {
126 if ( consumer != null && !isDisabled() )
127 {
128 consumer.consumeLine( line );
129 }
130 }
131 }