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

org.refcodes.codec.BaseEncoder Maven / Gradle / Ivy

Go to download

Artifact with encoding and decoding (not in terms of encryption/decryption) implementations (codecs) such as BASE64 encoding / decoding.

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.codec;

import java.io.IOException;
import java.io.OutputStream;

import org.refcodes.codec.BaseMetricsAccessor.BaseMetricsBuilder;
import org.refcodes.codec.BaseMetricsAccessor.BaseMetricsProperty;
import org.refcodes.component.AbstractConnectableAutomaton;
import org.refcodes.component.ConnectionComponent;
import org.refcodes.component.Openable;
import org.refcodes.io.ByteTransmitterDecorator;
import org.refcodes.io.BytesReceiver;
import org.refcodes.io.BytesSource;
import org.refcodes.io.BytesTransmitter;
import org.refcodes.io.OutputStreamBytesTransmitter;

/**
 * The {@link BaseEncoder} implements the {@link BaseBuilder} functionality in
 * terms of a {@link BytesTransmitter}.
 * 
 * Make sure to call {@link #close()} when done as the final padding bytes are
 * appended to the end!
 */
public class BaseEncoder extends AbstractConnectableAutomaton implements BaseMetricsProperty, BaseMetricsBuilder, Encoder {

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

	private static final int BYTE_MASK = 0xFF;
	private static final int BYTES_PER_INT = 4;
	private static final int BITS_PER_BYTE = 8;
	private static final int BITS_PER_INT = BITS_PER_BYTE * BYTES_PER_INT;

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

	private BytesTransmitter _byteSender;
	private BaseMetrics _baseMetrics = BaseMetricsConfig.BASE64;
	private byte[] _buffer = new byte[_baseMetrics.getBytesPerInt()];
	private int _index = 0;

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

	/**
	 * Constructs the {@link BaseEncoder} instance using the provided
	 * {@link OutputStream} to receive the encoded data.
	 *
	 * @param aOutputStream the output stream
	 * 
	 * @throws IOException throw in case using the {@link OutputStream} caused
	 *         I/O related problems.
	 */
	public BaseEncoder( OutputStream aOutputStream ) throws IOException {
		this( new OutputStreamBytesTransmitter( aOutputStream ) );
	}

	/**
	 * Constructs the {@link BaseEncoder} instance using the provided
	 * {@link OutputStream} to receive the encoded data.
	 *
	 * @param aOutputStream the output stream
	 * @param aBaseMetrics The {@link BaseMetrics} to use.
	 * 
	 * @throws IOException throw in case using the {@link OutputStream} caused
	 *         I/O related problems.
	 */
	public BaseEncoder( OutputStream aOutputStream, BaseMetrics aBaseMetrics ) throws IOException {
		this( new OutputStreamBytesTransmitter( aOutputStream ), aBaseMetrics );
	}

	/**
	 * Constructs the {@link BaseEncoder} instance using the provided
	 * {@link BytesSource} to receive the encoded data.
	 * 
	 * @param aByteConsumer The {@link BytesSource} to be fed with the encoded
	 *        data.
	 */
	public BaseEncoder( BytesSource aByteConsumer ) {
		try {
			open( new ByteTransmitterDecorator( aByteConsumer ) );
		}
		catch ( IOException ignore ) {}
	}

	/**
	 * Constructs the {@link BaseEncoder} instance using the provided
	 * {@link BytesTransmitter} to receive the encoded data.
	 * 
	 * @param aByteSender The {@link BytesTransmitter} to be fed with the
	 *        encoded data.
	 * 
	 * @throws IOException in case opening or accessing an open line
	 *         (connection, junction, link) caused problems.
	 */
	public BaseEncoder( BytesTransmitter aByteSender ) throws IOException {
		open( aByteSender );
	}

	/**
	 * Constructs the {@link BaseEncoder} instance using the provided
	 * {@link OutputStreamBytesTransmitter} to receive the encoded data.
	 * 
	 * @param aOutputStreamBytesTransmitter The
	 *        {@link OutputStreamBytesTransmitter} to use.
	 * @param aBaseMetrics The {@link BaseMetrics} to use.
	 * 
	 * @throws IOException in case opening or accessing an open line
	 *         (connection, junction, link) caused problems.
	 */
	public BaseEncoder( OutputStreamBytesTransmitter aOutputStreamBytesTransmitter, BaseMetrics aBaseMetrics ) throws IOException {
		this( aOutputStreamBytesTransmitter );
		setBaseMetrics( aBaseMetrics );
	}

	/**
	 * Explicit default constructor.
	 */
	protected BaseEncoder() {}

	// /////////////////////////////////////////////////////////////////////////
	// INJECTION:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * {@inheritDoc}
	 */
	@Override
	public BaseMetrics getBaseMetrics() {
		return _baseMetrics;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setBaseMetrics( BaseMetrics aBaseMetrics ) {
		_baseMetrics = aBaseMetrics;
		_buffer = new byte[_baseMetrics.getBytesPerInt()];
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public BaseEncoder withBaseMetrics( BaseMetrics aBaseMetrics ) {
		setBaseMetrics( aBaseMetrics );
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void transmitByte( byte aByte ) throws IOException {
		_buffer[_index % _baseMetrics.getBytesPerInt()] = aByte;
		_index++;
		if ( _index % _baseMetrics.getBytesPerInt() == 0 ) {
			toEncodedText( 0 );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void transmitBytes( byte[] aDatagram ) throws IOException {
		for ( byte eData : aDatagram ) {
			transmitByte( eData );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void transmitBytes( byte[] aDatagram, int aOffset, int aLength ) throws IOException {
		for ( int i = aOffset; i < aOffset + aLength; i++ ) {
			transmitByte( aDatagram[i] );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void flush() throws IOException {
		_byteSender.flush();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * Make sure to call {@link #close()} when done as the final padding bytes
	 * are appended to the end!
	 */
	@Override
	public synchronized void close() throws IOException {
		// int theMod = _index % _baseCodecMetrics.getBytesPerInt();
		// int theTrailingBytes = (theMod == 0) ? 0 : _baseCodecMetrics.getBytesPerInt() - theMod;
		final int theTrailingBytes = _baseMetrics.toPaddingCharsNumber( _index );
		try {
			if ( theTrailingBytes != 0 ) {
				while ( _index % _baseMetrics.getBytesPerInt() != 0 ) {
					_buffer[_index % _baseMetrics.getBytesPerInt()] = 0;
					_index++;
				}
				toEncodedText( theTrailingBytes );
				for ( int i = 0; i < theTrailingBytes; i++ ) {
					_byteSender.transmitByte( (byte) ( _baseMetrics.getPaddingChar() & 0xFF ) );
				}
			}
		}
		catch ( IOException e ) {
			throw new IOException( "Unable to finish off encoding.", e );
		}

		try {
			_byteSender.flush();
			_byteSender.close();
		}
		catch ( IOException e ) {
			throw new IOException( "Unable to close the output stream <" + _byteSender + ">.", e );
		}
		super.close();
	}

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

	/**
	 * Open.
	 *
	 * @param aConnection the connection
	 * 
	 * @throws IOException the open exception
	 */
	protected void open( BytesSource aConnection ) throws IOException {
		if ( aConnection instanceof BytesReceiver ) {
			_byteSender = (BytesTransmitter) aConnection;

		}
		else {
			_byteSender = new ByteTransmitterDecorator( aConnection );
		}
		if ( !_byteSender.isOpened() ) {
			if ( _byteSender instanceof Openable ) {
				( (Openable) _byteSender ).open();
			}
			else {
				throw new IOException( "The provided connection is in status <" + _byteSender.getConnectionStatus() + "> but does not provide the <" + Openable.class.getName() + "> interface." );
			}
		}
		open();
	}

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

	/**
	 * To encoded text.
	 *
	 * @param aTrailingBytes the trailing bytes
	 * 
	 * @throws IOException the open exception
	 */
	private void toEncodedText( int aTrailingBytes ) throws IOException {
		int theWord = toWord( _buffer, 0, _baseMetrics );
		theWord <<= ( BITS_PER_BYTE * ( BYTES_PER_INT - _baseMetrics.getBytesPerInt() ) );
		for ( int i = 0; i < _baseMetrics.getDigitsPerInt() - aTrailingBytes; i++ ) {
			final int eByte = ( theWord >> ( BITS_PER_INT - _baseMetrics.getBitsPerDigit() ) ) & _baseMetrics.getDigitMask();
			_byteSender.transmitByte( (byte) ( _baseMetrics.toChar( eByte ) & 0xFF ) );
			theWord <<= _baseMetrics.getBitsPerDigit();
		}
	}

	/**
	 * To word.
	 *
	 * @param aDecodedData the decoded data
	 * @param aOffset the offset
	 * @param aBaseMetrics the base metrics
	 * 
	 * @return the int
	 */
	private static int toWord( byte[] aDecodedData, int aOffset, BaseMetrics aBaseMetrics ) {
		int eWord = 0;
		for ( int i = 0; i < aBaseMetrics.getBytesPerInt(); i++ ) {
			eWord <<= BITS_PER_BYTE;
			if ( aOffset + i < aDecodedData.length ) {
				eWord |= (int) aDecodedData[aOffset + i] & BYTE_MASK;
			}
		}
		return eWord;
	}

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

	/**
	 * The {@link BaseEncoderConnection} implements the {@link BaseEncoder}
	 * functionality in terms of a {@link ConnectionComponent}. In addition to
	 * the {@link BaseEncoder} it provides means to open a dedicated
	 * {@link BytesSource} connection.
	 */
	public static class BaseEncoderConnection extends BaseEncoder implements ConnectionComponent {

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

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void open( BytesSource aConnection ) throws IOException {
			super.open( aConnection );
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy