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

org.refcodes.io.AbstractPrefetchInputStreamByteReceiver 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")
// together with the GPL linking exception applied; as being applied by the GNU
// Classpath ("http://www.gnu.org/software/classpath/license.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.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.refcodes.component.ConnectionComponent.ConnectionAutomaton;
import org.refcodes.component.ConnectionOpenable;
import org.refcodes.component.ConnectionStatus;
import org.refcodes.controlflow.ControlFlowUtility;
import org.refcodes.controlflow.RetryTimeout;
import org.refcodes.data.DaemonLoopSleepTime;
import org.refcodes.data.RetryLoopCount;
import org.refcodes.mixin.Disposable;

/**
 * Abstract implementation of the {@link BytesReceiver} interface. As of the
 * prefetching functionality, a separate daemon thread (retrieved via an
 * {@link ExecutorService}) reads from the provided {@link InputStream} and
 * places the datagrams into a datagram queue until the datagram queue's
 * capacity is reached. Datagrams are read by the {@link #receiveByte()}
 * ({@link #receiveAllBytes()}) by them methods popping the datagrams from the
 * datagram queue. If the queue is empty, then the {@link #receiveByte()} (
 * {@link #receiveAllBytes()}) method is blocked until the daemon thread places
 * new datagrams into the queue.
 * 
 * @see AbstractBytesReceiver
 */
public abstract class AbstractPrefetchInputStreamByteReceiver extends AbstractBytesReceiver {

	// /////////////////////////////////////////////////////////////////////////
	// STATICS:
	// /////////////////////////////////////////////////////////////////////////

	private static final Logger LOGGER = Logger.getLogger( AbstractPrefetchInputStreamByteReceiver.class.getName() );

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

	private ObjectInputStream _objectInputStream = null;
	private ExecutorService _executorService;
	private IoStreamReceiverDaemon _ioStreamReceiverDaemon = null;
	private boolean _isDaemonAlive = false;

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

	/**
	 * Creates an {@link AbstractPrefetchInputStreamByteReceiver}.
	 */
	public AbstractPrefetchInputStreamByteReceiver() {
		this( DATAGRAM_QUEUE_SIZE, null );
	}

	/**
	 * Creates an {@link AbstractPrefetchInputStreamByteReceiver} using the
	 * given {@link ExecutorService} required for thread generation in an JEE
	 * environment.
	 * 
	 * @param aExecutorService The {@link ExecutorService} to be used, when null
	 *        then an {@link ExecutorService} something line
	 *        {@link Executors#newCachedThreadPool()} is then retrieved.
	 */
	public AbstractPrefetchInputStreamByteReceiver( ExecutorService aExecutorService ) {
		this( DATAGRAM_QUEUE_SIZE, aExecutorService );
	}

	/**
	 * Creates an {@link AbstractPrefetchInputStreamByteReceiver} using the
	 * given datagram queue capacity.
	 * 
	 * @param aQueueCapacity The capacity of the prefetch queue before it blocks
	 *        until data is read via {@link #receiveByte()} (
	 *        {@link #receiveAllBytes()}).
	 */
	public AbstractPrefetchInputStreamByteReceiver( int aQueueCapacity ) {
		this( aQueueCapacity, null );
	}

	/**
	 * Creates an {@link AbstractPrefetchInputStreamByteReceiver} using the
	 * given {@link ExecutorService} required for thread generation in an JEE
	 * environment.
	 * 
	 * @param aQueueCapacity The capacity of the prefetch queue before it blocks
	 *        until data is read via {@link #receiveByte()} (
	 *        {@link #receiveAllBytes()}).
	 * @param aExecutorService The {@link ExecutorService} to be used, when null
	 *        then an {@link ExecutorService} something line
	 *        {@link Executors#newCachedThreadPool()} is then retrieved.
	 */
	public AbstractPrefetchInputStreamByteReceiver( int aQueueCapacity, ExecutorService aExecutorService ) {
		if ( aExecutorService == null ) {
			_executorService = ControlFlowUtility.createCachedExecutorService( true );
		}
		else {
			_executorService = ControlFlowUtility.toManagedExecutorService( aExecutorService );
		}
	}

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

	/**
	 * {@inheritDoc}
	 */
	@Override
	public synchronized void close() throws IOException {
		if ( !isClosed() ) {
			super.close();
			if ( _ioStreamReceiverDaemon != null ) {
				_ioStreamReceiverDaemon.dispose();
				_ioStreamReceiverDaemon = null;
			}
			try {
				if ( _objectInputStream != null ) {
					_objectInputStream.close();
				}
			}
			catch ( IOException e ) {
				throw new IOException( "Unable to close receiver (connection status is <" + getConnectionStatus() + ">) as of a causing exception <" + e.getClass().getName() + "> !", e );
			}
		}
	}

	// /////////////////////////////////////////////////////////////////////////
	// HOOKS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * Open, see also {@link ConnectionOpenable#open(Object)}.
	 *
	 * @param aInputStream the input stream
	 * 
	 * @throws IOException the open exception
	 */
	protected synchronized void open( InputStream aInputStream ) throws IOException {
		if ( isOpened() ) {
			throw new IOException( "Unable to open the connection is is is already OPEN (connection status is <" + getConnectionStatus() + ">)." );
		}
		try {
			if ( !( aInputStream instanceof BufferedInputStream ) ) {
				_objectInputStream = new SerializableObjectInputStream( new BufferedInputStream( aInputStream ) );
			}
			else {
				_objectInputStream = new SerializableObjectInputStream( aInputStream );
			}
		}
		catch ( IOException aException ) {
			if ( !isThrownAsOfAlreadyClosed( aException ) ) {
				throw new IOException( "Unable to open the I/O stream receiver as of a causing exception.", aException );
			}
		}
		_ioStreamReceiverDaemon = new IoStreamReceiverDaemon();
		// LOGGER.debug( "Starting I/O stream receiver daemon <" + _ioStreamReceiverDaemon.getClass().getName() + ">." );
		// Open the connection before daemon starts as daemon tests for an open connection:
		setConnectionStatus( ConnectionStatus.OPENED );
		_executorService.execute( _ioStreamReceiverDaemon );
		if ( !_isDaemonAlive ) {
			final RetryTimeout theRetryTimeout = new RetryTimeout( DaemonLoopSleepTime.NORM.getTimeMillis(), RetryLoopCount.NORM_NUM_RETRY_LOOPS.getValue() );
			while ( !_isDaemonAlive ) {
				theRetryTimeout.nextRetry();
			}
		}
	}

	/**
	 * Checks if is openable. See also
	 * {@link ConnectionAutomaton#isOpenable(Object)}.
	 *
	 * @param aInputStream the input stream
	 * 
	 * @return true, if is openable
	 */
	protected boolean isOpenable( InputStream aInputStream ) {
		return aInputStream == null ? false : !isOpened();
	}

	// /////////////////////////////////////////////////////////////////////////
	// INNER CLASSES:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * The {@link IoStreamReceiverDaemon} waits for datagrams and puts them into
	 * the queue.
	 */
	private class IoStreamReceiverDaemon implements Runnable, Disposable {

		private boolean _isDisposed = false;

		// /////////////////////////////////////////////////////////////////////
		// DAEMON:
		// /////////////////////////////////////////////////////////////////////

		@Override
		public void run() {
			try {
				int eWord;
				_isDaemonAlive = true;
				while ( !_isDisposed && isOpened() ) {
					eWord = _objectInputStream.read();
					pushDatagram( (byte) ( eWord & 0xFF ) );
				}
			}
			catch ( IOException e1 ) {
				synchronized ( AbstractPrefetchInputStreamByteReceiver.this ) {
					if ( AbstractPrefetchInputStreamByteReceiver.this.isOpened() ) {
						try {
							if ( !( e1 instanceof EOFException ) ) {
								LOGGER.log( Level.WARNING, "Unable to read datagram from sender (connection status is a" + getConnectionStatus() + ">) as of a causing exception <" + e1.getClass().getName() + ">!", e1 );
							}
							close();
						}
						catch ( IOException e2 ) {
							LOGGER.log( Level.WARNING, "Unable to close malfunctioning connection as of as of a causing exception <" + e2.getClass().getName() + ">!", e2 );
						}
					}
				}
			}
			finally {
				_isDaemonAlive = false;
				// LOGGER.log( Level.WARNING, "Terminating I/O stream receiver daemon <" + IoStreamReceiverDaemon.this.getClass().getName() + ">." );
			}
		}

		/**
		 * Dispose.
		 */
		@Override
		public void dispose() {
			_isDisposed = true;
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy