org.refcodes.io.AbstractReceiver 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.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.refcodes.component.AbstractConnectableAutomaton;
import org.refcodes.component.CloseException;
import org.refcodes.component.OpenException;
import org.refcodes.controlflow.RetryCounter;
import org.refcodes.controlflow.RetryCounterImpl;
import org.refcodes.data.IoRetryCount;
import org.refcodes.data.LoopSleepTime;
import org.refcodes.mixin.Loggable;
/**
* The {@link AbstractReceiver} is a base abstract implementation of the
* {@link Receiver} interface providing common functionality for concrete real
* live {@link ByteDatagramReceiver} and {@link ByteBlockReceiver} (=
* {@link Receiver}) implementations.
*
* A blocking queue is used internally to which received datagrams are put via
* {@link #pushDatagram(Serializable)} and which can be retrieved via
* {@link #readDatagram()}. The {@link #pushDatagram(Serializable)} method is
* your hook when extending this class.
*
* Make sure your code fetches the datagrams quick enough to prevent filling up
* of the queue. In case the queue is filled up, adding elements via
* {@link #pushDatagram(Serializable)} to the queue is blocked until elements
* are taken from the queue via {@link #readDatagram()}. So cautions are taken
* to prevent a memory leak.
*
* @param The type of the datagram to be operated with.
*/
public abstract class AbstractReceiver extends AbstractConnectableAutomaton implements Receiver, Loggable {
// /////////////////////////////////////////////////////////////////////////
// CONSTANTS:
// /////////////////////////////////////////////////////////////////////////
public static final int DATAGRAM_QUEUE_SIZE = 1024;
// /////////////////////////////////////////////////////////////////////////
// VARIABLES:
// /////////////////////////////////////////////////////////////////////////
private LinkedBlockingQueue _datagramQueue;
// /////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS:
// /////////////////////////////////////////////////////////////////////////
/**
* Constructs a {@link AbstractReceiver} with a default sized blocking queue
* enabling a maximum of {@link #DATAGRAM_QUEUE_SIZE} datagrams.
* -------------------------------------------------------------------------
* Make sure your code fetches the datagrams quick enough to prevent filling
* up of the queue. In case the queue is filled up, adding elements via
* {@link #pushDatagram(Serializable)} to the queue is blocked until
* elements are taken from the queue via {@link #readDatagram()}.
*/
public AbstractReceiver() {
_datagramQueue = new LinkedBlockingQueue( DATAGRAM_QUEUE_SIZE );
}
/**
* Constructs a {@link AbstractReceiver} with a custom sized blocking queue
* enabling a maximum of datagrams as specified by the capacity parameter.
* -------------------------------------------------------------------------
* Make sure your code fetches the datagrams quick enough to prevent filling
* up of the queue. In case the queue is filled up, adding elements via
* {@link #pushDatagram(Serializable)} to the queue is blocked until
* elements are taken from the queue via {@link #readDatagram()}.
*
* @param aCapacity The capacity of the queue holding the received
* datagrams.
*/
public AbstractReceiver( int aCapacity ) {
_datagramQueue = new LinkedBlockingQueue( aCapacity );
}
// /////////////////////////////////////////////////////////////////////////
// METHODS:
// /////////////////////////////////////////////////////////////////////////
/**
* {@inheritDoc}
*/
@Override
public DATA readDatagram() throws OpenException, InterruptedException {
if ( _datagramQueue.isEmpty() && !isOpened() ) {
throw new OpenException( "Unable to read datagram as the connection is NOT OPEN; connection status is " + getConnectionStatus() + "." );
}
return _datagramQueue.take();
}
/**
* Read datagrams.
*
* @return the DAT a[]
* @throws OpenException the open exception
* @throws InterruptedException the interrupted exception
*/
@SuppressWarnings("unchecked")
@Override
public DATA[] readDatagrams() throws OpenException, InterruptedException {
if ( _datagramQueue.isEmpty() && !isOpened() ) {
throw new OpenException( "Unable to read datagram as the connection is NOT OPEN; connection status is " + getConnectionStatus() + "." );
}
List theBytes = new ArrayList<>();
_datagramQueue.drainTo( theBytes );
return theBytes.toArray( ((DATA[]) new Object[theBytes.size()]) );
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDatagram() throws OpenException {
// Enable the caller to get all elements from the queue:
// if ( _datagramQueue.isEmpty() && !isOpened() ) { throw new
// OpenException( "Unable to read datagram as the connection is NOT
// OPEN; connection status is " + getConnectionStatus() + "." ); }
return !_datagramQueue.isEmpty();
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws CloseException {
if ( isOpened() ) {
super.close();
releaseAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void releaseAll() {
synchronized ( _datagramQueue ) {
_datagramQueue.notifyAll();
}
}
// /////////////////////////////////////////////////////////////////////////
// HOOKS:
// /////////////////////////////////////////////////////////////////////////
/**
* Pushes a datagram into the receiver and puts it into the blocking queue
* containing the so far received datagrams. Them datagrams can be retrieved
* via {@link #readDatagram()}: use {@link #hasDatagram()} to test
* beforehand whether there is a datagram available.
*
* @param aDatagram The datagram to be pushed at the end of the blocking
* queue; to be retrieved with the {@link #readDatagram()} method.
* @throws OpenException the open exception
*/
protected void pushDatagram( DATA aDatagram ) throws OpenException {
if ( !isOpened() ) {
throw new OpenException( "Unable to push datagram <" + aDatagram.getClass().getName() + "> as the connection is NOT OPEN; connection status is " + getConnectionStatus() + "." );
}
RetryCounter theRetryCounter = new RetryCounterImpl( IoRetryCount.MAX.getValue() );
try {
while ( !_datagramQueue.offer( aDatagram, LoopSleepTime.MAX.getMillis(), TimeUnit.MILLISECONDS ) && theRetryCounter.nextRetry() ) {
warn( "Trying to offer (add) a datagram to the datagram queue, though the queue is full, this is retry # <" + theRetryCounter.getRetryCount() + ">, aborting after <" + theRetryCounter.getRetryNumber() + "> retries. Retrying now after a delay of <" + (LoopSleepTime.MAX.getMillis() / 1000) + "> seconds..." );
if ( !theRetryCounter.hasNextRetry() ) {
throw new OpenException( "Unable to process the datagram after <" + theRetryCounter.getRetryNumber() + "> retries, aborting retries, dismissing datagram \"" + aDatagram.toString() + "\"!", null, null );
}
}
}
catch ( InterruptedException ignored ) {}
}
/**
* Pushes datagrams into the receiver and puts them into the blocking queue
* containing the so far received datagrams. Them datagrams can be retrieved
* via {@link #readDatagram()}: use {@link #hasDatagram()} to test
* beforehand whether there is a datagram available.
*
* @param aDatagrams The datagrams to be pushed at the end of the blocking
* queue; to be retrieved with the {@link #readDatagram()} method.
* @throws OpenException the open exception
*/
protected void pushDatagrams( DATA[] aDatagrams ) throws OpenException {
for ( DATA eData : aDatagrams ) {
pushDatagram( eData );
}
}
/**
* Pushes datagrams into the receiver and puts them into the blocking queue
* containing the so far received datagrams. Them datagrams can be retrieved
* via {@link #readDatagram()}: use {@link #hasDatagram()} to test
* beforehand whether there is a datagram available.
*
* @param aDatagrams The datagrams to be pushed at the end of the blocking
* queue; to be retrieved with the {@link #readDatagram()} method.
* @param aOffset The offset to start taking data from to be pushed.
* @param aLength The number of elements to be pushed from the offset
* onwards.
* @throws OpenException the open exception
*/
protected void pushDatagrams( DATA[] aDatagrams, int aOffset, int aLength ) throws OpenException {
for ( int i = aOffset; i < aOffset + aLength; i++ ) {
pushDatagram( aDatagrams[i] );
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy