aboutsummaryrefslogtreecommitdiffstats
path: root/lib/src/main/java/com/trilead/ssh2/StreamGobbler.java
blob: 1e87bb184ef50882e7ceeb0c71506f1dd5292cb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package com.trilead.ssh2;

import java.io.IOException;
import java.io.InputStream;

/**
 * A <code>StreamGobbler</code> is an InputStream that uses an internal worker
 * thread to constantly consume input from another InputStream. It uses a buffer
 * to store the consumed data. The buffer size is automatically adjusted, if needed.
 * <p>
 * This class is sometimes very convenient - if you wrap a session's STDOUT and STDERR
 * InputStreams with instances of this class, then you don't have to bother about
 * the shared window of STDOUT and STDERR in the low level SSH-2 protocol,
 * since all arriving data will be immediatelly consumed by the worker threads.
 * Also, as a side effect, the streams will be buffered (e.g., single byte
 * read() operations are faster).
 * <p>
 * Other SSH for Java libraries include this functionality by default in
 * their STDOUT and STDERR InputStream implementations, however, please be aware
 * that this approach has also a downside:
 * <p>
 * If you do not call the StreamGobbler's <code>read()</code> method often enough
 * and the peer is constantly sending huge amounts of data, then you will sooner or later
 * encounter a low memory situation due to the aggregated data (well, it also depends on the Java heap size).
 * Joe Average will like this class anyway - a paranoid programmer would never use such an approach.
 * <p>
 * The term "StreamGobbler" was taken from an article called "When Runtime.exec() won't",
 * see http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html.
 * 
 * @author Christian Plattner, plattner@trilead.com
 * @version $Id: StreamGobbler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
 */

public class StreamGobbler extends InputStream
{
	class GobblerThread extends Thread
	{
		public void run()
		{
			byte[] buff = new byte[8192];

			while (true)
			{
				try
				{
					int avail = is.read(buff);

					synchronized (synchronizer)
					{
						if (avail <= 0)
						{
							isEOF = true;
							synchronizer.notifyAll();
							break;
						}
						
						int space_available = buffer.length - write_pos;
						
						if (space_available < avail)
						{
							/* compact/resize buffer */

							int unread_size = write_pos - read_pos;
							int need_space = unread_size + avail;

							byte[] new_buffer = buffer;

							if (need_space > buffer.length)
							{
								int inc = need_space / 3;
								inc = (inc < 256) ? 256 : inc;
								inc = (inc > 8192) ? 8192 : inc;
								new_buffer = new byte[need_space + inc];
							}
							
							if (unread_size > 0)
								System.arraycopy(buffer, read_pos, new_buffer, 0, unread_size);

							buffer = new_buffer;
							
							read_pos = 0;
							write_pos = unread_size;
						}
						
						System.arraycopy(buff, 0, buffer, write_pos, avail);
						write_pos += avail;

						synchronizer.notifyAll();
					}	
				}
				catch (IOException e)
				{
					synchronized (synchronizer)
					{
						exception = e;
						synchronizer.notifyAll();
						break;
					}
				}
			}
		}
	}

	private InputStream is;
	private GobblerThread t;

	private Object synchronizer = new Object();

	private boolean isEOF = false;
	private boolean isClosed = false;
	private IOException exception = null;

	private byte[] buffer = new byte[2048];
	private int read_pos = 0;
	private int write_pos = 0;

	public StreamGobbler(InputStream is)
	{
		this.is = is;
		t = new GobblerThread();
		t.setDaemon(true);
		t.start();
	}

	public int read() throws IOException
	{
		synchronized (synchronizer)
		{
			if (isClosed)
				throw new IOException("This StreamGobbler is closed.");

			while (read_pos == write_pos)
			{
				if (exception != null)
					throw exception;

				if (isEOF)
					return -1;

				try
				{
					synchronizer.wait();
				}
				catch (InterruptedException e)
				{
				}
			}

			int b = buffer[read_pos++] & 0xff;

			return b;
		}
	}

	public int available() throws IOException
	{
		synchronized (synchronizer)
		{
			if (isClosed)
				throw new IOException("This StreamGobbler is closed.");

			return write_pos - read_pos;
		}
	}

	public int read(byte[] b) throws IOException
	{
		return read(b, 0, b.length);
	}

	public void close() throws IOException
	{
		synchronized (synchronizer)
		{
			if (isClosed)
				return;
			isClosed = true;
			isEOF = true;
			synchronizer.notifyAll();
			is.close();
		}
	}

	public int read(byte[] b, int off, int len) throws IOException
	{
		if (b == null)
			throw new NullPointerException();

		if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0) || (off > b.length))
			throw new IndexOutOfBoundsException();

		if (len == 0)
			return 0;

		synchronized (synchronizer)
		{
			if (isClosed)
				throw new IOException("This StreamGobbler is closed.");

			while (read_pos == write_pos)
			{
				if (exception != null)
					throw exception;

				if (isEOF)
					return -1;

				try
				{
					synchronizer.wait();
				}
				catch (InterruptedException e)
				{
				}
			}

			int avail = write_pos - read_pos;

			avail = (avail > len) ? len : avail;

			System.arraycopy(buffer, read_pos, b, off, avail);

			read_pos += avail;

			return avail;
		}
	}
}