InputStreamPumper.java

  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.  *      https://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. package org.apache.commons.exec;

  18. import java.io.InputStream;
  19. import java.io.OutputStream;

  20. import org.apache.commons.exec.util.DebugUtils;

  21. /**
  22.  * Copies all data from an System.input stream to an output stream of the executed process.
  23.  */
  24. public class InputStreamPumper implements Runnable {

  25.     /**
  26.      * Sleep time in milliseconds.
  27.      */
  28.     public static final int SLEEPING_TIME = 100;

  29.     /** The input stream to pump from. */
  30.     private final InputStream is;

  31.     /** The output stream to pmp into. */
  32.     private final OutputStream os;

  33.     /** Flag to stop the stream pumping. */
  34.     private volatile boolean stop;

  35.     /**
  36.      * Create a new stream pumper.
  37.      *
  38.      * @param is input stream to read data from.
  39.      * @param os output stream to write data to.
  40.      */
  41.     public InputStreamPumper(final InputStream is, final OutputStream os) {
  42.         this.is = is;
  43.         this.os = os;
  44.         this.stop = false;
  45.     }

  46.     /**
  47.      * Copies data from the input stream to the output stream. Terminates as soon as the input stream is closed or an error occurs.
  48.      */
  49.     @Override
  50.     public void run() {
  51.         try {
  52.             while (!stop) {
  53.                 while (is.available() > 0 && !stop) {
  54.                     os.write(is.read());
  55.                 }
  56.                 os.flush();
  57.                 Thread.sleep(SLEEPING_TIME);
  58.             }
  59.         } catch (final Exception e) {
  60.             final String msg = "Got exception while reading/writing the stream";
  61.             DebugUtils.handleException(msg, e);
  62.         }
  63.     }

  64.     /**
  65.      * Requests processing to stop.
  66.      */
  67.     public void stopProcessing() {
  68.         stop = true;
  69.     }

  70. }