All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.refcodes.io.AvailableInputStream Maven / Gradle / Ivy

Go to download

Artifact with commonly used I/O functionality and for connection related issues such as receiving or transmitting data in a unified way.

There is a newer version: 3.3.8
Show newest version
// /////////////////////////////////////////////////////////////////////////////
// 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.EOFException;
import java.io.IOException;
import java.io.InputStream;

import org.refcodes.data.IoTimeout;
import org.refcodes.exception.TimeoutIOException;

/**
 * The {@link AvailableInputStream} decorates an {@link InputStream} with
 * time-out functionality using the {@link InputStream#available()} method. This
 * decorator works only when the decorated {@link InputStream} returns realistic
 * values when calling {@link InputStream#available()}. This is most probably
 * the case e.g. for serial communication (TTY/COM) as those devices usually
 * buffer for incoming bytes. If this cannot be guaranteed, please use the
 * {@link TimeoutInputStream}! The benefit of the {@link AvailableInputStream}
 * over the {@link TimeoutInputStream} is that the {@link AvailableInputStream}
 * does not use any additional threads for asynchronous operation so it is a
 * good fit for IoT devices!
 */
public class AvailableInputStream extends TimeoutInputStream {

	// /////////////////////////////////////////////////////////////////////////
	// VARIABLES:
	// /////////////////////////////////////////////////////////////////////////

	private Object _monitor;

	// /////////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * Constructs a {@link AvailableInputStream} 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 AvailableInputStream( InputStream aInputStream, long aTimeoutMillis ) {
		this( aInputStream, aTimeoutMillis, null );
	}

	/**
	 * Constructs a {@link AvailableInputStream} 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 AvailableInputStream( InputStream aInputStream, Long aTimeoutMillis ) {
		this( aInputStream, aTimeoutMillis, null );
	}

	/**
	 * Constructs a {@link AvailableInputStream} decorating an
	 * {@link InputStream} with additional timeout functionality.
	 * 
	 * @param aInputStream The {@link InputStream} to be decorated.
	 * @param aMonitor The monitor to use when waiting the poll loop time. This
	 *        is useful required available data can be read before the poll loop
	 *        time expires. E.g. an underlying system might call
	 *        {@link Object#notifyAll()} on the monitor as soon as it received
	 *        new data.
	 */
	public AvailableInputStream( InputStream aInputStream, Object aMonitor ) {
		this( aInputStream, -1, aMonitor );
	}

	/**
	 * Constructs a {@link AvailableInputStream} decorating an
	 * {@link InputStream} with additional timeout functionality.
	 * 
	 * @param aInputStream The {@link InputStream} to be decorated.
	 */
	public AvailableInputStream( InputStream aInputStream ) {
		this( aInputStream, -1, null );
	}

	/**
	 * Constructs a {@link AvailableInputStream} 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 aMonitor The monitor to use when waiting the poll loop time. This
	 *        is useful required available data can be read before the poll loop
	 *        time expires. E.g. an underlying system might call
	 *        {@link Object#notifyAll()} on the monitor as soon as it received
	 *        new data.
	 */
	public AvailableInputStream( InputStream aInputStream, long aTimeoutMillis, Object aMonitor ) {
		super( aInputStream, aTimeoutMillis );
		_monitor = aMonitor != null ? aMonitor : this;
	}

	// /////////////////////////////////////////////////////////////////////////
	// METHODS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int read( long aTimeoutMillis ) throws IOException {
		if ( _isClosed ) {
			return -1;
		}
		try {
			waitForBytesAvailable( 1, aTimeoutMillis );
			return _inputStream.read();
		}
		catch ( EOFException e ) {
			return -1;
		}
		catch ( IOException e ) {
			if ( _isClosed ) {
				return -1;
			}
			throw e;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int read( byte[] b, int off, int len, long aTimeoutMillis ) throws IOException {
		try {
			waitForBytesAvailable( len, aTimeoutMillis );
			return _inputStream.read( b, off, len );
		}
		catch ( EOFException e ) {
			return -1; // !!!
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int read( byte[] b, long aTimeoutMillis ) throws IOException {

		if ( b != null && b.length != 0 ) {
			final int len = b.length;
			try {
				waitForBytesAvailable( len, aTimeoutMillis );
				return _inputStream.read( b );
			}
			catch ( EOFException e ) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int readNBytes( byte[] b, int off, int len, long aTimeoutMillis ) throws IOException {
		if ( b != null && b.length != 0 ) {
			try {
				waitForBytesAvailable( len, aTimeoutMillis );
				return _inputStream.readNBytes( b, off, len );
			}
			catch ( EOFException e ) {
				return -1;
			}
		}
		return 0;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public byte[] readNBytes( int len, long aTimeoutMillis ) throws IOException {
		if ( len > 0 ) {
			waitForBytesAvailable( len, aTimeoutMillis );
			return _inputStream.readNBytes( len );
		}
		return new byte[0];
	}

	// /////////////////////////////////////////////////////////////////////////
	// HELPER:
	// /////////////////////////////////////////////////////////////////////////

	private void waitForBytesAvailable( int aNumberOfBytes, long aTimeoutMillis ) throws IOException {
		if ( _isClosed ) {
			throw new IOException( "The stream has already been closed!" );
		}

		// Peek into stream |-->
		if ( available() != -1 && _inputStream.markSupported() ) {
			_inputStream.mark( 1 );
			int theValue = 0;
			try {
				theValue = _inputStream.read();
				if ( theValue != -1 ) {
					return;
				}
			}
			catch ( Exception ignore ) {}
			finally {
				_inputStream.reset();
			}
			if ( theValue == -1 ) {
				throw new EOFException( "Reached end of file (stream), no more data available!" );
			}
		}
		// Peek into stream <--|

		if ( aTimeoutMillis != -1 ) {
			final long theStartTimeMs = System.currentTimeMillis();
			while ( !_isClosed && available() < aNumberOfBytes && System.currentTimeMillis() - theStartTimeMs < aTimeoutMillis ) {
				synchronized ( _monitor ) {
					try {
						_monitor.wait( IoTimeout.toTimeoutSleepLoopTimeInMs( aTimeoutMillis ) );
					}
					catch ( InterruptedException e ) {
						throw new IOException( "Interrupted while trying to read <" + aNumberOfBytes + "> number of bytes after <" + ( System.currentTimeMillis() - theStartTimeMs ) + "> milliseconds (with a given timeout of <" + aTimeoutMillis + "> milliseconds)!", e );
					}
				}
			}
			if ( _isClosed ) {
				throw new IOException( "Connection was closed after <" + ( System.currentTimeMillis() - theStartTimeMs ) + "> milliseconds (with a given timeout of <" + aTimeoutMillis + "> milliseconds) while trying to read <" + aNumberOfBytes + "> number of bytes." );
			}
			if ( available() < aNumberOfBytes ) {
				throw new TimeoutIOException( aTimeoutMillis, "Operation timed out after <" + aTimeoutMillis + "> milliseconds while trying to read <" + aNumberOfBytes + "> number of bytes." );
			}
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy