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