J. Duke | 319a3b9 | 2007-12-01 00:00:00 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 1998-1999 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, |
| 20 | * CA 95054 USA or visit www.sun.com if you need additional information or |
| 21 | * have any questions. |
| 22 | */ |
| 23 | |
| 24 | /** |
| 25 | * |
| 26 | */ |
| 27 | |
| 28 | import java.io.*; |
| 29 | |
| 30 | /** |
| 31 | * Pipe output of one stream into input of another. |
| 32 | */ |
| 33 | public class StreamPipe extends Thread { |
| 34 | |
| 35 | private InputStream in; |
| 36 | private OutputStream out; |
| 37 | private String preamble; |
| 38 | private static Object lock = new Object(); |
| 39 | private static int count = 0; |
| 40 | |
| 41 | public StreamPipe(InputStream in, OutputStream out, String name) { |
| 42 | super(name); |
| 43 | this.in = in; |
| 44 | this.out = out; |
| 45 | this.preamble = "# "; |
| 46 | } |
| 47 | |
| 48 | public void run() { |
| 49 | BufferedReader r = new BufferedReader(new InputStreamReader(in), 1); |
| 50 | BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out)); |
| 51 | byte[] buf = new byte[256]; |
| 52 | boolean bol = true; // beginning-of-line |
| 53 | int count; |
| 54 | |
| 55 | try { |
| 56 | String line; |
| 57 | while ((line = r.readLine()) != null) { |
| 58 | w.write(preamble); |
| 59 | w.write(line); |
| 60 | w.newLine(); |
| 61 | w.flush(); |
| 62 | } |
| 63 | } catch (IOException e) { |
| 64 | System.err.println("*** IOException in StreamPipe.run:"); |
| 65 | e.printStackTrace(); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | public static void plugTogether(InputStream in, OutputStream out) { |
| 70 | String name = null; |
| 71 | |
| 72 | synchronized (lock) { |
| 73 | name = "TestLibrary: StreamPipe-" + (count ++ ); |
| 74 | } |
| 75 | |
| 76 | Thread pipe = new StreamPipe(in, out, name); |
| 77 | pipe.setDaemon(true); |
| 78 | pipe.start(); |
| 79 | } |
| 80 | } |