org.refcodes.io.TimeoutInputStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of refcodes-io Show documentation
Show all versions of refcodes-io Show documentation
Artifact with commonly used I/O functionality and for connection related
issues such as receiving or transmitting data in a unified way.
// /////////////////////////////////////////////////////////////////////////////
// REFCODES.ORG
// /////////////////////////////////////////////////////////////////////////////
// This code is copyright (c) by Siegfried Steiner, Munich, Germany, distributed
// on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and licen-
// sed under the following (see "http://en.wikipedia.org/wiki/Multi-licensing")
// licenses:
// -----------------------------------------------------------------------------
// GNU General Public License, v3.0 ("http://www.gnu.org/licenses/gpl-3.0.html")
// -----------------------------------------------------------------------------
// Apache License, v2.0 ("http://www.apache.org/licenses/TEXT-2.0")
// -----------------------------------------------------------------------------
// Please contact the copyright holding author(s) of the software artifacts in
// question for licensing issues not being covered by the above listed licenses,
// also regarding commercial licensing models or regarding the compatibility
// with other open source licenses.
// /////////////////////////////////////////////////////////////////////////////
package org.refcodes.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.refcodes.exception.TimeoutIOException;
import org.refcodes.mixin.ReadTimeoutMillisAccessor;
/**
* The {@link TimeoutInputStream} decorates an {@link InputStream} with time-out
* functionality using {@link CompletableFuture} functionality. This decorator
* works despite the decorated {@link InputStream} returning realistic values
* when calling {@link InputStream#available()}. If this can be guaranteed, you
* may use the {@link AvailableInputStream}! The benefit of the
* {@link AvailableInputStream} over the {@link TimeoutInputStream} is that the
* {@link AvailableInputStream} does not use any additional threads for
* asynchronous operation! Additional thread is skipped in case the
* {@link TimeoutInputStream} timeout is -1 or the available (as of
* {@link #available()}) number of bytes is greater or equal to the number of
* bytes to be read.
*/
public class TimeoutInputStream extends InputStream implements ReadTimeoutMillisAccessor {
// /////////////////////////////////////////////////////////////////////////
// VARIABLES:
// /////////////////////////////////////////////////////////////////////////
protected InputStream _inputStream;
protected long _readTimeoutMillis;
protected boolean _isClosed = false;
private ExecutorService _executorService = null;
// /////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS:
// /////////////////////////////////////////////////////////////////////////
/**
* Constructs a {@link TimeoutInputStream} decorating an {@link InputStream}
* with additional timeout functionality.
*
* @param aInputStream The {@link InputStream} to be decorated.
* @param aTimeoutMillis The default timeout for read operations not
* explicitly called with a timeout argument. With a value of -1
* timeout handling is disabled (blocking mode).
*/
public TimeoutInputStream( InputStream aInputStream, long aTimeoutMillis ) {
this( aInputStream, aTimeoutMillis, null );
}
/**
* Constructs a {@link TimeoutInputStream} decorating an {@link InputStream}
* with additional timeout functionality.
*
* @param aInputStream The {@link InputStream} to be decorated.
*
* @param aExecutorService The {@link ExecutorService} to be used when
* creating threads.
*/
public TimeoutInputStream( InputStream aInputStream, ExecutorService aExecutorService ) {
this( aInputStream, -1, aExecutorService );
}
/**
* Constructs a {@link TimeoutInputStream} decorating an {@link InputStream}
* with additional timeout functionality.
*
* @param aInputStream The {@link InputStream} to be decorated.
*/
public TimeoutInputStream( InputStream aInputStream ) {
this( aInputStream, -1, null );
}
/**
* Constructs a {@link TimeoutInputStream} decorating an {@link InputStream}
* with additional timeout functionality.
*
* @param aInputStream The {@link InputStream} to be decorated.
* @param aTimeoutMillis The default timeout for read operations not
* explicitly called with a timeout argument. With a value of -1
* timeout handling is disabled (blocking mode).
*
* @param aExecutorService The {@link ExecutorService} to be used when
* creating threads.
*/
public TimeoutInputStream( InputStream aInputStream, long aTimeoutMillis, ExecutorService aExecutorService ) {
_inputStream = aInputStream;
_readTimeoutMillis = aTimeoutMillis;
_executorService = aExecutorService;
}
// /////////////////////////////////////////////////////////////////////////
// METHODS:
// /////////////////////////////////////////////////////////////////////////
/**
* {@inheritDoc}
*
* Caution: The timeout (as of {@link #getReadTimeoutMillis()}) is being
* applied! A timeout value of -1
when calling
* {@link #read(long)} disables the timeout!
*/
@Override
public int read() throws IOException {
return read( _readTimeoutMillis );
}
/**
* {@inheritDoc}
*
* Caution: The timeout (as of {@link #getReadTimeoutMillis()}) is being
* applied! A timeout value of -1
when calling
* {@link #read(byte[], int, int, long)} disables the timeout!
*/
@Override
public int read( byte[] b, int off, int len ) throws IOException {
return read( b, off, len, _readTimeoutMillis );
}
/**
* {@inheritDoc}
*
* Caution: The timeout (as of {@link #getReadTimeoutMillis()}) is being
* applied! A timeout value of -1
when calling
* {@link #read(byte[], long)} disables the timeout!
*/
@Override
public int read( byte[] b ) throws IOException {
return read( b, _readTimeoutMillis );
}
/**
* {@inheritDoc}
*
* Caution: The timeout (as of {@link #getReadTimeoutMillis()}) is being
* applied! A timeout value of -1
when calling
* {@link #readNBytes(byte[], int, int, long)} disables the timeout!
*/
@Override
public int readNBytes( byte[] b, int off, int len ) throws IOException {
return readNBytes( b, off, len, _readTimeoutMillis );
}
/**
* {@inheritDoc}
*
* Caution: The timeout (as of {@link #getReadTimeoutMillis()}) is being
* applied! A timeout value of -1
when calling
* {@link #readNBytes(int, long)} disables the timeout!
*/
@Override
public byte[] readNBytes( int len ) throws IOException {
return readNBytes( len, _readTimeoutMillis );
}
/**
* {@inheritDoc}
*/
@Override
public int available() throws IOException {
return _inputStream.available();
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
_isClosed = true;
_inputStream.close();
super.close();
}
/**
* {@inheritDoc}
*/
@Override
public void mark( int readlimit ) {
_inputStream.mark( readlimit );
}
/**
* {@inheritDoc}
*/
@Override
public boolean markSupported() {
return _inputStream.markSupported();
}
/**
* {@inheritDoc}
*/
@Override
public void reset() throws IOException {
_inputStream.reset();
}
/**
* Enriches the {@link #read()} method with a timeout. This methods blocks
* till the result is available and can be returned or the timeout is
* reached. A timeout of -1 disables the timeout.
*
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @return The next byte of data, or -1 if the end of the stream is reached.
*
* @throws IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public int read( long aTimeoutMillis ) throws IOException {
return timeout( _inputStream::read, 1, -1, aTimeoutMillis );
}
/**
* Enriches the {@link #read(byte[], int, int)} method with a timeout. This
* methods blocks till the result is available and can be returned or the
* timeout is reached. A timeout of -1 disables the timeout.
*
* @param b The byte array into which the data is read.
* @param off The start offset in b at which the data is written.
* @param len The maximum number of bytes to read.
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @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 IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public int read( byte[] b, int off, int len, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.read( b, off, len ), len, -1, aTimeoutMillis );
}
/**
* Enriches the {@link #read(byte[])} method with a timeout. This methods
* blocks till the result is available and can be returned or the timeout is
* reached. A timeout of -1 disables the timeout. Calling this method has
* the same effect a read(b, 0, b.length)
, so we try to read as
* many bytes as the buffer's length is.
*
* @param b The byte array into which the data is read.
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @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 IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public int read( byte[] b, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.read( b ), b.length, -1, aTimeoutMillis );
}
/**
* Enriches the {@link #readNBytes(byte[], int, int)} method with a timeout.
* This methods blocks till the result is available and can be returned or
* the timeout is reached. A timeout of -1 disables the timeout.
*
* @param b the byte array into which the data is read
* @param off the start offset in b
at which the data is
* written
* @param len the maximum number of bytes to read
* @param aTimeoutMillis The timeout in milliseconds.
*
* @return the actual number of bytes read into the buffer
*
* @throws IOException if an I/O error occurs
* @throws NullPointerException if b
is null
* @throws IndexOutOfBoundsException If off
is negative,
* len
is negative, or len
is greater than
* b.length - off
*/
public int readNBytes( byte[] b, int off, int len, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.readNBytes( b, off, len ), len, -1, aTimeoutMillis );
}
/**
* Enriches the {@link #readNBytes(int)} method with a timeout. This methods
* blocks till the result is available and can be returned or the timeout is
* reached. A timeout of -1 disables the timeout.
*
* @param len the maximum number of bytes to read
* @param aTimeoutMillis The timeout in milliseconds.
*
* @return The byte array containing the bytes read from this input stream
*
* @throws IOException Signals that an I/O exception has occurred.
*/
public byte[] readNBytes( int len, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.readNBytes( len ), len, null, aTimeoutMillis );
}
/**
* Enriches the {@link #skip(long)} method with a timeout. This methods
* blocks till the result is available and can be returned or the timeout is
* reached. A timeout of -1 disables the timeout.
*
* @param n the number of bytes to be skipped.
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @return the actual number of bytes skipped which might be zero.
*
* @throws IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public long skip( long n, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.skip( n ), n, (long) -1, aTimeoutMillis );
}
/**
* Enriches the {@link #skipNBytes(long)} method with a timeout. This
* methods blocks till the result is available and can be returned or the
* timeout is reached. A timeout of -1 disables the timeout.
*
* @param n the number of bytes to be skipped.
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @throws IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public void skipNBytes( long n, long aTimeoutMillis ) throws IOException {
timeout( () -> _inputStream.skipNBytes( n ), n, aTimeoutMillis );
}
/**
* Enriches the {@link #transferTo(OutputStream)} method with a timeout.
* This methods blocks till the result is available and can be returned or
* the timeout is reached. A timeout of -1 disables the timeout.
*
* @param out the output stream, non-null
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @return the number of bytes transferred
*
* @throws IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public long transferTo( OutputStream out, long aTimeoutMillis ) throws IOException {
return timeout( () -> _inputStream.transferTo( out ), available(), (long) -1, aTimeoutMillis );
}
/**
* Enriches the {@link #readAllBytes()} method with a timeout. This methods
* blocks till the result is available and can be returned or the timeout is
* reached. A timeout of -1 disables the timeout.
*
* @param aTimeoutMillis The timeout in milliseconds to wait for the next
* byte available.With a value of -1 timeout handling is disabled
* (blocking mode).
*
* @return a byte array containing the bytes read from this input stream
*
* @throws IOException thrown in case of according I/O related problems or
* an expired timeout.
*/
public byte[] readAllBytes( long aTimeoutMillis ) throws IOException {
return timeout( _inputStream::readAllBytes, available(), null, aTimeoutMillis );
}
/**
* {@inheritDoc}
*/
@Override
public long getReadTimeoutMillis() {
return _readTimeoutMillis;
}
// /////////////////////////////////////////////////////////////////////////
// HELPER:
// /////////////////////////////////////////////////////////////////////////
private R timeout( Reader aReader, long aLength, R aDefaultResult, long aTimeoutMillis ) throws IOException {
if ( _isClosed ) {
return aDefaultResult;
}
else if ( _readTimeoutMillis == -1 || available() >= aLength ) {
return aReader.read();
}
else {
final CompletableFuture theFuture = new CompletableFuture<>();
theFuture.completeAsync( () -> {
try {
return aReader.read();
}
catch ( Exception e ) {
theFuture.completeExceptionally( e );
return aDefaultResult;
}
}, _executorService != null ? _executorService : theFuture.defaultExecutor() );
try {
return theFuture.get( aTimeoutMillis, TimeUnit.MILLISECONDS );
}
catch ( InterruptedException | ExecutionException | TimeoutException e ) {
throw new TimeoutIOException( aTimeoutMillis, "Operation timed out after <" + aTimeoutMillis + "> milliseconds while trying to read <" + aLength + "> number of bytes.", e );
}
}
}
private void timeout( Runner aRunner, long aLength, long aTimeoutMillis ) throws IOException {
if ( _isClosed ) {
return;
}
else if ( _readTimeoutMillis == -1 || available() >= aLength ) {
aRunner.run();
}
else {
final CompletableFuture theFuture = new CompletableFuture<>();
theFuture.completeAsync( () -> {
try {
aRunner.run();
return null;
}
catch ( Exception e ) {
theFuture.completeExceptionally( e );
return null;
}
}, _executorService != null ? _executorService : theFuture.defaultExecutor() );
try {
theFuture.get( aTimeoutMillis, TimeUnit.MILLISECONDS );
}
catch ( InterruptedException | ExecutionException | TimeoutException e ) {
throw new TimeoutIOException( aTimeoutMillis, "Operation timed out after <" + aTimeoutMillis + "> milliseconds while trying to read <" + aLength + "> number of bytes.", e );
}
}
}
// /////////////////////////////////////////////////////////////////////////
// INNER CLASSES:
// /////////////////////////////////////////////////////////////////////////
@FunctionalInterface
private interface Reader {
T read() throws IOException;
}
@FunctionalInterface
private interface Runner {
void run() throws IOException;
}
}