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

org.refcodes.io.AbstractPrefetchInputStreamReceiver 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 and licensed
// 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/LICENSE-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.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.refcodes.component.CloseException;
import org.refcodes.component.ConnectionComponent.ConnectionAutomaton;
import org.refcodes.component.ConnectionOpenable;
import org.refcodes.component.ConnectionStatus;
import org.refcodes.component.OpenException;
import org.refcodes.controlflow.ControlFlowUtility;
import org.refcodes.controlflow.RetryTimeout;
import org.refcodes.controlflow.RetryTimeoutImpl;
import org.refcodes.data.DaemonLoopSleepTime;
import org.refcodes.data.RetryLoopCount;
import org.refcodes.exception.ExceptionUtility;
import org.refcodes.mixin.Disposable;
import org.refcodes.mixin.Loggable;

/**
 * Abstract implementation of the {@link Receiver} 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 #readDatagram()} ({@link #readDatagrams()})
 * by them methods popping the datagrams from the datagram queue.
 * 
 * If the queue is empty, then the {@link #readDatagram()} (
 * {@link #readDatagrams()}) method is blocked until the daemon thread places
 * new datagrams into the queue.
 * 
 * See also {@link AbstractReceiver}.
 *
 * @param  The type of the datagram to be operated with.
 */
public abstract class AbstractPrefetchInputStreamReceiver extends AbstractReceiver implements Loggable {

	// /////////////////////////////////////////////////////////////////////////
	// CONSTANTS:
	// /////////////////////////////////////////////////////////////////////////

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

	private ObjectInputStream _objectInputStream = null;

	private ExecutorService _executorService;

	private IoStreamReceiverDaemon _ioStreamReceiverDaemon = null;

	private boolean _isDaemonAlive = false;

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

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

	/**
	 * Creates an {@link AbstractPrefetchInputStreamReceiver} 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 AbstractPrefetchInputStreamReceiver( ExecutorService aExecutorService ) {
		this( DATAGRAM_QUEUE_SIZE, aExecutorService );
	}

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

	/**
	 * Creates an {@link AbstractPrefetchInputStreamReceiver} 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 #readDatagram()} (
	 *        {@link #readDatagrams()}).
	 * 
	 * @param aExecutorService The {@link ExecutorService} to be used, when null
	 *        then an {@link ExecutorService} something line
	 *        {@link Executors#newCachedThreadPool()} is then retrieved.
	 */
	public AbstractPrefetchInputStreamReceiver( int aQueueCapacity, ExecutorService aExecutorService ) {
		if ( aExecutorService == null ) {
			_executorService = ControlFlowUtility.createCachedExecutorService( true );
		}
		else {
			_executorService = ControlFlowUtility.toManagedExecutorService( aExecutorService );
		}
	}

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

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

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

	/**
	 * Open, see also {@link ConnectionOpenable#open(Object)}.
	 *
	 * @param aInputStream the input stream
	 * @throws OpenException the open exception
	 */
	protected synchronized void open( InputStream aInputStream ) throws OpenException {
		if ( isOpened() ) {
			throw new OpenException( "Unable to open the connection is is is ALREADY OPEN; connection status is " + getConnectionStatus() + "." );
		}
		try {
			if ( !(aInputStream instanceof BufferedInputStream) ) {
				_objectInputStream = new SerializableObjectInputStreamImpl( new BufferedInputStream( aInputStream ) );
			}
			else {
				_objectInputStream = new SerializableObjectInputStreamImpl( aInputStream );
			}
		}
		catch ( IOException aException ) {
			if ( !ExceptionUtility.isThrownAsOfAlreadyClosed( aException ) ) throw new OpenException( "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 ) {
			RetryTimeout theRetryTimeout = new RetryTimeoutImpl( DaemonLoopSleepTime.NORM.getMillis(), 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 ) {
		if ( aInputStream == null ) {
			return false;
		}
		return !isOpened();
	}

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

	// /////////////////////////////////////////////////////////////////////////
	// 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:
		// /////////////////////////////////////////////////////////////////////

		/**
		 * Run.
		 */
		@SuppressWarnings("unchecked")
		@Override
		public void run() {
			try {
				Object eObject = null;
				_isDaemonAlive = true;
				while ( !_isDisposed && isOpened() ) {
					try {
						eObject = _objectInputStream.readObject();
						pushDatagram( (DATA) eObject );
					}
					catch ( ClassNotFoundException | ClassCastException aException ) {
						warn( "Unable to read datagram from sender as of a causing exception; connection status is " + getConnectionStatus(), aException );
					}
				}
			}
			catch ( IOException aException ) {
				synchronized ( AbstractPrefetchInputStreamReceiver.this ) {
					if ( AbstractPrefetchInputStreamReceiver.this.isOpened() ) {
						try {
							if ( !(aException instanceof EOFException) ) {
								warn( "Unable to read datagram from sender as of a causing exception; connection status is " + getConnectionStatus(), aException );
							}
							close();
						}
						catch ( CloseException e ) {
							warn( "Unable to close malfunctioning connection as of: " + ExceptionUtility.toMessage( e ), e );
						}
					}
				}
			}
			finally {
				_isDaemonAlive = false;
				debug( "Terminating I/O stream receiver daemon <" + IoStreamReceiverDaemon.this.getClass().getName() + ">." );
			}
		}

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy