View Javadoc
1   package org.sentrysoftware.jawk.jrt;
2   
3   /*-
4    * ╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲
5    * Jawk
6    * ჻჻჻჻჻჻
7    * Copyright (C) 2006 - 2023 Sentry Software
8    * ჻჻჻჻჻჻
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation, either version 3 of the
12   * License, or (at your option) any later version.
13   *
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Lesser Public License for more details.
18   *
19   * You should have received a copy of the GNU General Lesser Public
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22   * ╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱╲╱
23   */
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.io.PrintStream;
28  
29  /**
30   * Relay data from an input stream to an output stream.
31   * A thread is created to do the work.
32   * <p>
33   * Jawk uses data pumps to relay stdin, stdout, and stderr
34   * of a spawned process (by, for example, system() or
35   * "cmd" | getline) to the stdin, stdout, and/or stderr
36   * of the calling process (the interpreter itself).
37   *
38   * @author Danny Daglas
39   */
40  public class DataPump implements Runnable {
41  
42  	private InputStream is;
43  	private PrintStream os;
44  
45  	/**
46  	 * Represents a data pump.
47  	 *
48  	 * @param in The input stream.
49  	 * @param out The output stream.
50  	 */
51  	public DataPump(InputStream in, PrintStream out) {
52  		this.is = in;
53  		this.os = out;
54  		//setDaemon(true);
55  	}
56  
57  	/**
58  	 * Allocate the data pump and start the thread.
59  	 *
60  	 * @param desc A human-readable description of this data pump.
61  	 *   It is part of the thread name, and, therefore, visible
62  	 *   upon a VM thread dump.
63  	 * @param in The input stream.
64  	 * @param out The output stream.
65  	 */
66  	public static void dump(String desc, InputStream in, PrintStream out) {
67  		new Thread(new DataPump(in, out), desc).start();
68  	}
69  
70  	/**
71  	 * {@inheritDoc}
72  	 *
73  	 * VM entry point for the thread. It performs the data
74  	 * relay.
75  	 */
76  	@Override
77  	public final void run() {
78  		try {
79  			byte[] b = new byte[4096];
80  			int len;
81  			while ((len = is.read(b, 0, b.length)) >= 0) {
82  				os.write(b, 0, len);
83  			}
84  		} catch (IOException ioe) {
85  			// ignore
86  		}
87  		try {
88  			is.close();
89  		} catch (IOException ioe) {}
90  	}
91  }