Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6d0d1806742879e357cff19a079c90de4902de3a (plain) (blame)
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
230
231
232
233
/*******************************************************************************
 * Copyright (c) 2000, 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     EclipseSource - modification after copying to ECF filetransfer provider
 *******************************************************************************/
package org.eclipse.ecf.provider.filetransfer.util;

import java.io.*;
import org.eclipse.core.runtime.*;
import org.eclipse.ecf.internal.provider.filetransfer.Activator;

/**
 * Polls a progress monitor periodically and handles timeouts over extended
 * durations. For this class to be effective, a high numAttempts should be
 * specified, and the underlying stream should time out frequently on reads
 * (every second or so).
 * 
 * Supports resuming partially completed operations after an
 * InterruptedIOException if the underlying stream does. Check the
 * bytesTransferred field to determine how much of the operation completed;
 * conversely, at what point to resume.
 */
public class PollingInputStream extends FilterInputStream {
	private int numAttempts;
	private IProgressMonitor monitor;
	private boolean cancellable;

	/**
	 * Creates a new polling input stream.
	 * 
	 * @param in
	 *            the underlying input stream
	 * @param numAttempts
	 *            the number of attempts before issuing an
	 *            InterruptedIOException, if 0, retries indefinitely until
	 *            canceled
	 * @param monitor
	 *            the progress monitor to be polled for cancellation
	 */
	public PollingInputStream(InputStream in, int numAttempts, IProgressMonitor monitor) {
		super(in);
		this.numAttempts = numAttempts;
		this.monitor = monitor;
		this.cancellable = true;
	}

	/**
	 * Wraps the underlying stream's method. It may be important to wait for an
	 * input stream to be closed because it holds an implicit lock on a system
	 * resource (such as a file) while it is open. Closing a stream may take
	 * time if the underlying stream is still servicing a previous request.
	 * 
	 * @throws OperationCanceledException
	 *             if the progress monitor is canceled
	 * @throws InterruptedIOException
	 *             if the underlying operation times out numAttempts times
	 */
	public void close() throws InterruptedIOException {
		int attempts = 0;
		try {
			readPendingInput();
		} catch (IOException e) {
			// We shouldn't get an exception when we're getting the available
			// input.
			// If we do, just log it so we can close.
			logError(e.getMessage(), e);
		} finally {
			boolean stop = false;
			while (!stop) {
				try {
					if (in != null)
						in.close();
					stop = true;
				} catch (InterruptedIOException e) {
					if (checkCancellation())
						throw new OperationCanceledException();
					if (++attempts == numAttempts)
						throw new InterruptedIOException("Timeout while closing input stream"); //$NON-NLS-1$
				} catch (IOException e) {
					// ignore it - see
					// https://bugs.eclipse.org/bugs/show_bug.cgi?id=203423#c10
				}
			}
		}
	}

	private void logError(String message, IOException e) {
		Activator.getDefault().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, message, e));
	}

	/**
	 * Wraps the underlying stream's method.
	 * 
	 * @return the next byte of data, or -1 if the end of the stream is reached.
	 * @throws OperationCanceledException
	 *             if the progress monitor is canceled
	 * @throws InterruptedIOException
	 *             if the underlying operation times out numAttempts times and
	 *             no data was received, bytesTransferred will be zero
	 * @throws IOException
	 *             if an i/o error occurs
	 */
	public int read() throws IOException {
		int attempts = 0;
		for (;;) {
			if (checkCancellation())
				throw new OperationCanceledException();
			try {
				return in.read();
			} catch (InterruptedIOException e) {
				if (++attempts == numAttempts)
					throw new InterruptedIOException("Timeout while reading input stream"); //$NON-NLS-1$
			}
		}
	}

	/**
	 * Wraps the underlying stream's method.
	 * 
	 * @param buffer
	 *            - the buffer into which the data is read.
	 * @param off
	 *            - the start offset of the data.
	 * @param len
	 *            - the maximum number of bytes read.
	 * @return the total number of bytes read into the buffer, or -1 if there is
	 *         no more data because the end of the stream has been reached.
	 * @throws OperationCanceledException
	 *             if the progress monitor is canceled
	 * @throws InterruptedIOException
	 *             if the underlying operation times out numAttempts times and
	 *             no data was received, bytesTransferred will be zero
	 * @throws IOException
	 *             if an i/o error occurs
	 */
	public int read(byte[] buffer, int off, int len) throws IOException {
		int attempts = 0;
		for (;;) {
			if (checkCancellation())
				throw new OperationCanceledException();
			try {
				return in.read(buffer, off, len);
			} catch (InterruptedIOException e) {
				if (e.bytesTransferred != 0)
					return e.bytesTransferred; // keep partial transfer
				if (++attempts == numAttempts)
					throw new InterruptedIOException("Timeout while reading input stream"); //$NON-NLS-1$
			}
		}
	}

	/**
	 * Wraps the underlying stream's method.
	 * 
	 * @param count
	 *            - the number of bytes to be skipped.
	 * @return the actual number of bytes skipped.
	 * @throws OperationCanceledException
	 *             if the progress monitor is canceled
	 * @throws InterruptedIOException
	 *             if the underlying operation times out numAttempts times and
	 *             no data was received, bytesTransferred will be zero
	 * @throws IOException
	 *             if an i/o error occurs
	 */
	public long skip(long count) throws IOException {
		int attempts = 0;
		for (;;) {
			if (checkCancellation())
				throw new OperationCanceledException();
			try {
				return in.skip(count);
			} catch (InterruptedIOException e) {
				if (e.bytesTransferred != 0)
					return e.bytesTransferred; // keep partial transfer
				if (++attempts == numAttempts)
					throw new InterruptedIOException("Timeout while reading input stream"); //$NON-NLS-1$
			}
		}
	}

	/**
	 * Reads any pending input from the input stream so that the stream can
	 * savely be closed.
	 */
	protected void readPendingInput() throws IOException {
		byte[] buffer = new byte[2048];
		while (true) {
			int available = in.available();
			if (available < 1)
				break;
			if (available > buffer.length)
				available = buffer.length;
			if (in.read(buffer, 0, available) < 1)
				break;
		}
	}

	/**
	 * Called to set whether cancellation will be checked by this stream.
	 * Turning cancellation checking off can be very useful for protecting
	 * critical portions of a protocol that shouldn't be interrupted. For
	 * example, it is often necessary to protect login sequences.
	 * 
	 * @param cancellable
	 *            a flag controlling whether this stream will check for
	 *            cancellation.
	 */
	public void setIsCancellable(boolean cancellable) {
		this.cancellable = cancellable;
	}

	/**
	 * Checked whether the monitor for this stream has been cancelled. If the
	 * cancellable flag is <code>false</code> then the monitor is never
	 * cancelled.
	 * 
	 * @return <code>true</code> if the monitor has been cancelled and
	 *         <code>false</code> otherwise.
	 */
	private boolean checkCancellation() {
		if (cancellable) {
			return monitor.isCanceled();
		}
		return false;
	}
}

Back to the top