1 /* 2 * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 import java.io.InputStream; 25 import java.io.InterruptedIOException; 26 import java.io.IOException; 27 import java.io.OutputStream; 28 29 /** 30 * Pipe output of one stream into input of another. 31 */ 32 public class StreamPipe extends Thread { 33 34 private InputStream in; 35 private OutputStream out; 36 37 private static Object countLock = new Object(); 38 private static int count = 0; 39 40 /** 41 * StreamPipe constructor : should only be called by plugTogether() method. 42 */ StreamPipe(InputStream in, OutputStream out, String name)43 private StreamPipe(InputStream in, OutputStream out, String name) { 44 super(name); 45 this.in = in; 46 this.out = out; 47 } 48 49 /** 50 * Creates a StreamPipe thread that copies in to out and returns 51 * the created instance. 52 */ plugTogether(InputStream in, OutputStream out)53 public static StreamPipe plugTogether(InputStream in, OutputStream out) { 54 String name; 55 56 synchronized (countLock) { 57 name = "java.rmi.testlibrary.StreamPipe-" + (count++); 58 } 59 60 StreamPipe pipe = new StreamPipe(in, out, name); 61 pipe.setDaemon(true); 62 pipe.start(); 63 return pipe; 64 } 65 66 // Starts redirection of streams. run()67 public void run() { 68 try { 69 byte[] buf = new byte[1024]; 70 71 while (true) { 72 int nr = in.read(buf); 73 if (nr == -1) 74 break; 75 out.write(buf, 0, nr); 76 } 77 } catch (InterruptedIOException iioe) { 78 // Thread interrupted during IO operation. Terminate StreamPipe. 79 return; 80 } catch (IOException e) { 81 System.err.println("*** IOException in StreamPipe.run:"); 82 e.printStackTrace(); 83 } 84 } 85 } 86