org.refcodes.io.AbstractPrefetchInputStreamByteReceiver 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 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.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.logger.RuntimeLogger;
import org.refcodes.logger.RuntimeLoggerFactorySingleton;
import org.refcodes.mixin.Disposable;
/**
* Abstract implementation of the {@link ByteReceiver} 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 AbstractByteReceiver
*/
public abstract class AbstractPrefetchInputStreamByteReceiver extends AbstractByteReceiver {
private static RuntimeLogger LOGGER = RuntimeLoggerFactorySingleton.createRuntimeLogger();
// /////////////////////////////////////////////////////////////////////////
// CONSTANTS:
// /////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////
// 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 #readDatagram()} (
* {@link #readDatagrams()}).
*
*/
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 #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 AbstractPrefetchInputStreamByteReceiver( int aQueueCapacity, ExecutorService aExecutorService ) {
if ( aExecutorService == null ) {
_executorService = ControlFlowUtility.createDaemonExecutorService();
}
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 a 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.getMilliseconds(), RetryLoopCount.NORM_NUM_RETRY_LOOPS.getNumber() );
while ( !_isDaemonAlive ) {
theRetryTimeout.nextRetry();
}
}
}
/**
* Checks if is openable. See also
* {@link ConnectionAutomaton#isOpenable(Object)}.
*
* @param aInputStream the a 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.
*/
@Override
public void run() {
try {
int eWord;
_isDaemonAlive = true;
while ( !_isDisposed && isOpened() ) {
eWord = _objectInputStream.read();
pushDatagram( (byte) (eWord & 0xFF) );
}
}
catch ( IOException aException ) {
synchronized ( AbstractPrefetchInputStreamByteReceiver.this ) {
if ( AbstractPrefetchInputStreamByteReceiver.this.isOpened() ) {
try {
if ( !(aException instanceof EOFException) ) {
LOGGER.warn( "Unable to read datagram from sender as of a causing exception; connection status is " + getConnectionStatus(), aException );
}
close();
}
catch ( CloseException e ) {
LOGGER.warn( "Unable to close malfunctioning connection as of: " + ExceptionUtility.toMessage( e ), e );
}
}
}
}
finally {
_isDaemonAlive = false;
// @formatter:off
// LOGGER.debug( "Terminating I/O stream receiver daemon <" + IoStreamReceiverDaemon.this.getClass().getName() + ">." );
// @formatter:on
}
}
/**
* Dispose.
*/
@Override
public void dispose() {
_isDisposed = true;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy