1 package org.codehaus.plexus.util.cli;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22
23
24
25
26
27
28
29 public class StreamFeeder
30 extends AbstractStreamHandler
31 {
32
33 private InputStream input;
34
35 private OutputStream output;
36
37 private volatile Throwable exception = null;
38
39
40
41
42
43
44
45 public StreamFeeder( InputStream input, OutputStream output )
46 {
47 super();
48 this.input = input;
49 this.output = output;
50 }
51
52 @Override
53 public void run()
54 {
55 try
56 {
57 feed();
58 }
59 catch ( Throwable ex )
60 {
61 if ( exception == null )
62 {
63 exception = ex;
64 }
65 }
66 finally
67 {
68 close();
69
70 synchronized ( this )
71 {
72 setDone();
73
74 this.notifyAll();
75 }
76 }
77 }
78
79 public void close()
80 {
81 if ( input != null )
82 {
83 synchronized ( input )
84 {
85 try
86 {
87 input.close();
88 }
89 catch ( IOException ex )
90 {
91 if ( exception == null )
92 {
93 exception = ex;
94 }
95 }
96
97 input = null;
98 }
99 }
100
101 if ( output != null )
102 {
103 synchronized ( output )
104 {
105 try
106 {
107 output.close();
108 }
109 catch ( IOException ex )
110 {
111 if ( exception == null )
112 {
113 exception = ex;
114 }
115 }
116
117 output = null;
118 }
119 }
120 }
121
122
123
124
125
126 public Throwable getException()
127 {
128 return exception;
129 }
130
131 private void feed()
132 throws IOException
133 {
134 boolean flush = false;
135 int data = input.read();
136
137 while ( !isDone() && data != -1 )
138 {
139 synchronized ( output )
140 {
141 if ( !isDisabled() )
142 {
143 output.write( data );
144 flush = true;
145 }
146
147 data = input.read();
148 }
149 }
150
151 if ( flush )
152 {
153 output.flush();
154 }
155 }
156
157 }