1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package org.apache.commons.exec;
21
22 import java.io.InputStream;
23 import java.io.OutputStream;
24
25 import org.apache.commons.exec.util.DebugUtils;
26
27 /**
28 * Copies all data from a {@code System.input} stream to an output stream of the executed process.
29 */
30 public class InputStreamPumper implements Runnable {
31
32 /**
33 * Sleep time in milliseconds.
34 */
35 public static final int SLEEPING_TIME = 100;
36
37 /** The input stream to pump from. */
38 private final InputStream is;
39
40 /** The output stream to pmp into. */
41 private final OutputStream os;
42
43 /** Flag to stop the stream pumping. */
44 private volatile boolean stop;
45
46 /**
47 * Create a new stream pumper.
48 *
49 * @param is input stream to read data from.
50 * @param os output stream to write data to.
51 */
52 public InputStreamPumper(final InputStream is, final OutputStream os) {
53 this.is = is;
54 this.os = os;
55 this.stop = false;
56 }
57
58 /**
59 * Copies data from the input stream to the output stream. Terminates as soon as the input stream is closed or an error occurs.
60 */
61 @Override
62 public void run() {
63 try {
64 while (!stop) {
65 while (is.available() > 0 && !stop) {
66 os.write(is.read());
67 }
68 os.flush();
69 Thread.sleep(SLEEPING_TIME);
70 }
71 } catch (final Exception e) {
72 final String msg = "Got exception while reading/writing the stream";
73 DebugUtils.handleException(msg, e);
74 }
75 }
76
77 /**
78 * Requests processing to stop.
79 */
80 public void stopProcessing() {
81 stop = true;
82 }
83
84 }