Java Code Examples for org.apache.mina.core.buffer.IoBuffer#getUnsignedShort()

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#getUnsignedShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private boolean processWriteCommand ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    final int registerNumber = data.getUnsignedShort ();
    final int operationId = data.getInt ();
    final Variant value = decodeVariant ( session, data );

    out.write ( new WriteCommand ( registerNumber, value, operationId ) );

    return true;
}
 
Example 2
Source File: ModbusRequestBlock.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void writeData ( final int blockAddress, byte[] data )
{
    if ( this.request.getType () != RequestType.HOLDING )
    {
        throw new IllegalStateException ( String.format ( "Modbus can only write data when the block is of type %s", RequestType.HOLDING ) );
    }
    if ( data.length == 2 )
    {
        final IoBuffer buffer = IoBuffer.wrap ( data );
        buffer.order ( this.dataOrder );
        final int value = buffer.getUnsignedShort ();
        this.slave.writeCommand ( new WriteSingleDataRequest ( this.transactionId.incrementAndGet (), this.slave.getSlaveAddress (), Constants.FUNCTION_CODE_WRITE_SINGLE_REGISTER, toWriteAddress ( blockAddress ), value ), this.request.getTimeout () );
    }
    else
    {
        data = ModbusProtocol.encodeData ( data, this.dataOrder ); // apply requested byte order
        this.slave.writeCommand ( new WriteMultiDataRequest ( this.transactionId.incrementAndGet (), this.slave.getSlaveAddress (), Constants.FUNCTION_CODE_WRITE_MULTIPLE_REGISTERS, toWriteAddress ( blockAddress ), data, data.length / 2 ), this.request.getTimeout () );
    }
    requestUpdate ();
}
 
Example 3
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private boolean processDataUpdate ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    final int count = data.getUnsignedShort ();
    final List<DataUpdate.Entry> entries = new ArrayList<DataUpdate.Entry> ( count );
    for ( int i = 0; i < count; i++ )
    {
        entries.add ( decodeDataUpdateEntry ( data, session ) );
    }

    out.write ( new DataUpdate ( entries ) );

    return true;
}
 
Example 4
Source File: RemotingClient.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Decode response received from remoting server.
 * 
 * @param data
 *            Result data to decode
 * @return Object deserialized from byte buffer data
 */
private Object decodeResult(IoBuffer data) {
    log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0));
    processHeaders(data);
    int count = data.getUnsignedShort();
    if (count != 1) {
        throw new RuntimeException("Expected exactly one result but got " + count);
    }
    Input input = new Input(data);
    String target = input.getString(); // expect "/onResult"
    log.debug("Target: {}", target);
    String nullString = input.getString(); // expect "null"
    log.debug("Null string: {}", nullString);
    // Read return value
    return Deserializer.deserialize(input, Object.class);
}
 
Example 5
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private DaveMessage decodeDataReadReply ( final IoBuffer parameters, final IoBuffer data )
{
    parameters.get (); // command code

    final short count = parameters.getUnsigned ();

    final Collection<Result> result = new LinkedList<Result> ();

    for ( int i = 0; i < count; i++ )
    {
        final short q = data.getUnsigned ();
        if ( q == 0xFF && data.remaining () > 4 )
        {
            final byte type = data.get ();
            int len = data.getUnsignedShort ();
            if ( type == 4 )
            {
                len >>= 3;
            }

            final IoBuffer valueData = IoBuffer.allocate ( len );
            data.get ( valueData.array () );
            result.add ( new Result ( valueData ) );

            if ( len % 2 != 0 && data.remaining () > 0 )
            {
                data.get ();
            }
        }
        else if ( q != 0xFF )
        {
            result.add ( new Result ( q ) );
        }
    }

    return new DaveReadResult ( result );
}
 
Example 6
Source File: AbstractDataSlave.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void processAnalogWrite ( final int startAddress, final int numRegisters, final byte[] rawData )
{
    final int[] regs = new int[numRegisters];
    final IoBuffer data = IoBuffer.wrap ( rawData );

    data.order ( this.order );

    for ( int i = 0; i < numRegisters; i++ )
    {
        regs[i] = data.getUnsignedShort ();
    }

    handleAnalogWrite ( startAddress, regs );
}
 
Example 7
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Decode a PDU as a master
 *
 * @param message
 *            the message PDU
 * @return the decoded messages
 * @throws IllegalStateException
 *             if the function code is not supported
 */
public static Object decodeAsMaster ( final Pdu message )
{
    final IoBuffer data = message.getData ();

    final byte functionCode = data.get ();

    logger.trace ( "Decoding functionCode = {}", functionCode );

    if ( ( functionCode & Constants.FUNCTION_CODE_ERROR_FLAG ) != 0 )
    {
        final byte exceptionCode = data.get ();
        final byte originalFunctionCode = (byte) ( functionCode & ~Constants.FUNCTION_CODE_ERROR_FLAG );
        logger.trace ( "EC = {}, FC = {}", exceptionCode, functionCode );
        return new ErrorResponse ( message.getTransactionId (), message.getUnitIdentifier (), originalFunctionCode, exceptionCode );
    }

    switch ( functionCode )
    {
        case Constants.FUNCTION_CODE_READ_COILS:
        case Constants.FUNCTION_CODE_READ_DISCRETE_INPUTS:
        case Constants.FUNCTION_CODE_READ_HOLDING_REGISTERS:
        case Constants.FUNCTION_CODE_READ_INPUT_REGISTERS:
            return new ReadResponse ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, readBytes ( data ) );
        case Constants.FUNCTION_CODE_WRITE_SINGLE_COIL:
        case Constants.FUNCTION_CODE_WRITE_SINGLE_REGISTER:
            return new WriteSingleDataResponse ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, data.getUnsignedShort (), readBytes ( data, 2 ) );
        case Constants.FUNCTION_CODE_WRITE_MULTIPLE_COILS:
        case Constants.FUNCTION_CODE_WRITE_MULTIPLE_REGISTERS:
            return new WriteMultiDataResponse ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, data.getUnsignedShort (), data.getUnsignedShort () );
        default:
            throw new IllegalStateException ( String.format ( "Function code %02x is not supported", functionCode ) );
    }
}
 
Example 8
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Decode a PDU as a slave
 *
 * @param message
 *            the message PDU
 * @return the decoded messages
 * @throws IllegalStateException
 *             if the function code is not supported
 */
public static Object decodeAsSlave ( final Pdu message ) throws ProtocolCodecException
{
    final IoBuffer data = message.getData ();

    final byte functionCode = data.get ();

    switch ( functionCode )
    {
        case Constants.FUNCTION_CODE_READ_COILS:
        case Constants.FUNCTION_CODE_READ_DISCRETE_INPUTS:
        case Constants.FUNCTION_CODE_READ_HOLDING_REGISTERS:
        case Constants.FUNCTION_CODE_READ_INPUT_REGISTERS:
            return new ReadRequest ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, data.getUnsignedShort (), data.getUnsignedShort () );
        case Constants.FUNCTION_CODE_WRITE_SINGLE_COIL:
        case Constants.FUNCTION_CODE_WRITE_SINGLE_REGISTER:
            return new WriteSingleDataRequest ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, data.getUnsignedShort (), readBytes ( data, 2 ) );
        case Constants.FUNCTION_CODE_WRITE_MULTIPLE_COILS:
        case Constants.FUNCTION_CODE_WRITE_MULTIPLE_REGISTERS:
            final int startAddress = data.getUnsignedShort ();
            final int numRegisters = data.getUnsignedShort (); /* number of registers */
            final byte num = data.get ();
            if ( data.remaining () != num )
            {
                throw new ProtocolCodecException ( String.format ( "Wrong amount of data. Announced %s (bytes), found %s (bytes)", num, data.remaining () ) );
            }
            final byte[] b = new byte[data.remaining ()];
            data.get ( b );
            return new WriteMultiDataRequest ( message.getTransactionId (), message.getUnitIdentifier (), functionCode, startAddress, b, numRegisters );
        default:
            throw new IllegalStateException ( String.format ( "Function code %02x is not supported", functionCode ) );
    }
}
 
Example 9
Source File: ModbusRtuDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void decodeTimeoutFrame ( final IoSession session, final IoBuffer currentFrame, final ProtocolDecoderOutput out )
{
    logger.trace ( "timeout () frame = {}", currentFrame.getHexDump () );

    if ( currentFrame.limit () <= Constants.RTU_HEADER_SIZE )
    {
        throw new ModbusProtocolError ( "frame must be at least 4 bytes long (address + data[] + crc low + crc high" );
    }

    currentFrame.order ( ByteOrder.LITTLE_ENDIAN );
    final int receivedCrc = currentFrame.getUnsignedShort ( currentFrame.limit () - 2 );
    currentFrame.order ( ByteOrder.BIG_ENDIAN );

    final int actualCrc = Checksum.crc16 ( currentFrame.array (), 0, currentFrame.limit () - 2 );
    if ( receivedCrc != actualCrc )
    {
        final String hd = currentFrame.getHexDump ();
        logger.info ( "CRC error - received: {}, calculated: {} - data: {}", receivedCrc, actualCrc, hd );
        throw new ChecksumProtocolException ( String.format ( "CRC error. received: %04x, but actually was: %04x - Data: %s", receivedCrc, actualCrc, hd ) );
    }

    currentFrame.position ( 0 );

    // get unit id
    final byte unitIdentifier = currentFrame.get ();

    final int len = currentFrame.limit () - ( 2 /*crc*/+ 1/*unit id*/);

    final IoBuffer pdu = IoBuffer.allocate ( len );
    for ( int i = 0; i < len; i++ )
    {
        pdu.put ( currentFrame.get () );
    }
    pdu.flip ();

    // decode and send
    logger.trace ( "Decoded PDU - data: {}", pdu.getHexDump () );
    out.write ( new Pdu ( 0, unitIdentifier, pdu ) );
}
 
Example 10
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private DataUpdate.Entry decodeDataUpdateEntry ( final IoBuffer data, final IoSession session ) throws ProtocolCodecException
{
    final int register = data.getUnsignedShort ();
    final byte missedUpdates = data.get ();
    final long timestamp = data.getLong ();
    final Set<DataUpdate.State> states = data.getEnumSetShort ( DataUpdate.State.class );

    final Variant value = decodeVariant ( session, data );

    return new DataUpdate.Entry ( register, value, timestamp, states, missedUpdates );
}
 
Example 11
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private int messageLength ( final IoBuffer data )
{
    final int len = data.getUnsignedShort ( data.position () + 3 );
    if ( data.remaining () < 5 + len )
    {
        return -1;
    }

    data.skip ( 5 );

    return len;
}
 
Example 12
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private BrowseAdded.Entry decodeBrowserAddEntry ( final IoBuffer data, final IoSession session ) throws ProtocolCodecException
{
    final short register = (short)data.getUnsignedShort ();
    // FIXME: validate if short works

    final byte b = data.get ();
    final DataType dataType = DataType.fromByte ( b );

    if ( dataType == null )
    {
        throw new ProtocolCodecException ( String.format ( "Data type %s is unkown", b ) );
    }

    final Set<BrowseAdded.Entry.Flags> flags = data.getEnumSet ( BrowseAdded.Entry.Flags.class );

    final CharsetDecoder decoder = Sessions.getCharsetDecoder ( session );

    try
    {
        final String name = data.getPrefixedString ( decoder );
        final String description = data.getPrefixedString ( decoder );
        final String unit = data.getPrefixedString ( decoder );
        return new BrowseAdded.Entry ( register, name, description, unit, dataType, flags );
    }
    catch ( final CharacterCodingException e )
    {
        throw new ProtocolCodecException ( e );
    }

}
 
Example 13
Source File: RemotingClient.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/**
 * Process any headers sent in the response.
 * 
 * @param in
 *            Byte buffer with response data
 */
protected void processHeaders(IoBuffer in) {
    log.debug("RemotingClient processHeaders - buffer limit: {}", (in != null ? in.limit() : 0));
    int version = in.getUnsignedShort(); // skip
    log.debug("Version: {}", version);
    // the version by now, AMF3 is not yet implemented
    int count = in.getUnsignedShort();
    log.debug("Count: {}", count);
    Input input = new Input(in);
    for (int i = 0; i < count; i++) {
        String name = input.getString();
        //String name = deserializer.deserialize(input, String.class);
        log.debug("Name: {}", name);
        boolean required = (in.get() == 0x01);
        log.debug("Required: {}", required);
        int len = in.getInt();
        log.debug("Length: {}", len);
        Object value = Deserializer.deserialize(input, Object.class);
        log.debug("Value: {}", value);

        // XXX: this is pretty much untested!!!
        if (RemotingHeader.APPEND_TO_GATEWAY_URL.equals(name)) {
            // Append string to gateway url
            appendToUrl = (String) value;
        } else if (RemotingHeader.REPLACE_GATEWAY_URL.equals(name)) {
            // Replace complete gateway url
            url = (String) value;
            // XXX: reset the <appendToUrl< here?
        } else if (RemotingHeader.PERSISTENT_HEADER.equals(name)) {
            // Send a new header with each following request
            if (value instanceof Map<?, ?>) {
                @SuppressWarnings("unchecked")
                Map<String, Object> valueMap = (Map<String, Object>) value;
                RemotingHeader header = new RemotingHeader((String) valueMap.get("name"), (Boolean) valueMap.get("mustUnderstand"), valueMap.get("data"));
                headers.put(header.name, header);
            } else {
                log.error("Expected Map but received {}", value);
            }
        } else {
            log.warn("Unsupported remoting header \"{}\" received with value \"{}\"", name, value);
        }
    }
}
 
Example 14
Source File: SumkProtocolDecoder.java    From sumk with Apache License 2.0 4 votes vote down vote up
protected boolean innerDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
		throws CharacterCodingException, ProtocolDecoderException {
	int protocol = in.getInt();
	if ((protocol & 0xFF000000) != Protocols.MAGIC) {
		if (Logs.rpc().isTraceEnabled()) {
			Logs.rpc().trace(in.getString(Profile.UTF8.newDecoder()));
		}
		throw new ProtocolDecoderException("error magic," + Integer.toHexString(protocol));
	}
	int prefixLength = 0, maxDataLength = 0;
	if ((protocol & Protocols.ONE) != 0) {
		prefixLength = 1;
		maxDataLength = 0xFF;
	} else if ((protocol & Protocols.TWO) != 0) {
		prefixLength = 2;
		maxDataLength = 0xFFFF;
	} else if ((protocol & Protocols.FOUR) != 0) {
		prefixLength = 4;
		maxDataLength = Protocols.MAX_LENGTH;
	} else {
		if (AppInfo.getBoolean("sumk.rpc.log.code.error", true)) {
			Logs.rpc().error("error byte length protocol," + Integer.toHexString(protocol));
		}
		throw new ProtocolDecoderException("error byte length protocol," + Integer.toHexString(protocol));
	}

	if (in.remaining() < prefixLength) {
		return false;
	}
	int dataSize = 0;
	switch (prefixLength) {
	case 1:
		dataSize = in.getUnsigned();
		break;
	case 2:
		dataSize = in.getUnsignedShort();
		break;
	case 4:
		dataSize = in.getInt();
		break;
	}
	if (dataSize < 0 || dataSize > maxDataLength) {
		throw new BufferDataException("dataLength: " + dataSize);
	}
	if (in.remaining() < dataSize) {
		return false;
	}

	byte[] bs = new byte[dataSize];
	in.get(bs);
	out.write(new ProtocolObject(protocol, bs));
	return true;
}
 
Example 15
Source File: UInt16Accessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Integer get ( final IoBuffer data, final int index )
{
    return data.getUnsignedShort ( index );
}
 
Example 16
Source File: ProtocolDecoderImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private boolean processWelcome ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput out ) throws ProtocolCodecException
{
    final int len = messageLength ( data );
    if ( len < 0 )
    {
        return false;
    }

    final EnumSet<Welcome.Features> features = data.getEnumSetShort ( Welcome.Features.class );

    logger.debug ( "Features: {}", features );

    final CharsetDecoder decoder = this.defaultCharset.newDecoder ();

    final int count = data.getUnsignedShort ();
    final Map<String, String> properties = new HashMap<String, String> ( count );

    for ( int i = 0; i < count; i++ )
    {
        try
        {
            final String key = data.getPrefixedString ( decoder );
            final String value = data.getPrefixedString ( decoder );

            properties.put ( key, value );
        }
        catch ( final CharacterCodingException e )
        {
            throw new ProtocolCodecException ( e );
        }
    }

    if ( features.contains ( Welcome.Features.LITTLE_ENDIAN ) )
    {
        logger.info ( "Setting little endian" );
        Sessions.setLittleEndian ( session );
    }

    out.write ( new Welcome ( features, properties ) );

    return true;
}
 
Example 17
Source File: DSRemotingClient.java    From red5-client with Apache License 2.0 4 votes vote down vote up
/**
 * Process any headers sent in the response.
 * 
 * @param in
 *            Byte buffer with response data
 */
@Override
protected void processHeaders(IoBuffer in) {
    log.debug("RemotingClient processHeaders - buffer limit: {}", (in != null ? in.limit() : 0));
    int version = in.getUnsignedShort(); // skip
    log.debug("Version: {}", version);
    // the version by now, AMF3 is not yet implemented
    int count = in.getUnsignedShort();
    log.debug("Count: {}", count);
    Input input = new Input(in);
    for (int i = 0; i < count; i++) {
        String name = input.getString();
        log.debug("Name: {}", name);
        boolean required = (in.get() == 0x01);
        log.debug("Required: {}", required);
        Object value = null;
        int len = in.getInt();
        log.debug("Length: {}", len);
        // look for junk bytes ff,ff,ff,ff
        if (len == -1) {
            in.get(); //02
            len = in.getShort();
            log.debug("Corrected length: {}", len);
            value = input.readString(len);
        } else {
            value = Deserializer.deserialize(input, Object.class);
        }
        log.debug("Value: {}", value);
        // XXX: this is pretty much untested!!!
        if (RemotingHeader.APPEND_TO_GATEWAY_URL.equals(name)) {
            // Append string to gateway url
            appendToUrl = (String) value;
        } else if (RemotingHeader.REPLACE_GATEWAY_URL.equals(name)) {
            // Replace complete gateway url
            url = (String) value;
            // XXX: reset the <appendToUrl< here?
        } else if (RemotingHeader.PERSISTENT_HEADER.equals(name)) {
            // Send a new header with each following request
            if (value instanceof Map<?, ?>) {
                @SuppressWarnings("unchecked")
                Map<String, Object> valueMap = (Map<String, Object>) value;
                RemotingHeader header = new RemotingHeader((String) valueMap.get("name"), (Boolean) valueMap.get("mustUnderstand"), valueMap.get("data"));
                headers.put(header.getName(), header);
            } else {
                log.error("Expected Map but received {}", value);
            }
        } else {
            log.warn("Unsupported remoting header \"{}\" received with value \"{}\"", name, value);
        }
    }
}
 
Example 18
Source File: TPKTFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void messageReceived ( final NextFilter nextFilter, final IoSession session, final Object message ) throws Exception
{
    if ( ! ( message instanceof IoBuffer ) )
    {
        nextFilter.messageReceived ( session, message );
        return;
    }

    final IoBuffer in = (IoBuffer)message;
    final IoBuffer sessionBuffer = getSessionBuffer ( session );

    // first add to the session buffer (may be optimized later)
    sessionBuffer.position ( sessionBuffer.limit () );
    sessionBuffer.put ( in );
    sessionBuffer.flip ();

    while ( sessionBuffer.remaining () >= 4 )
    {
        final int len = sessionBuffer.getUnsignedShort ( 2 );
        if ( sessionBuffer.remaining () < len )
        {
            logger.debug ( "Next packet requires {} bytes", new Object[] { len } );
            // not enough data for body
            return;
        }

        // convert
        final IoBuffer data = IoBuffer.allocate ( len - 4 );
        sessionBuffer.get (); // version
        sessionBuffer.get (); // reserved
        sessionBuffer.getUnsignedShort (); // length

        sessionBuffer.get ( data.array () );

        nextFilter.messageReceived ( session, data );

        logger.debug ( "{} bytes left in session buffer", sessionBuffer.remaining () );
    }

    if ( sessionBuffer.hasRemaining () )
    {
        sessionBuffer.compact ();
    }
    else
    {
        sessionBuffer.clear ().flip ();
    }
}
 
Example 19
Source File: DaveFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private DaveMessage decode ( final IoBuffer buffer )
{
    final byte start = buffer.get ();
    if ( start != PACKET_START_MAGIC )
    {
        throw new IllegalStateException ( String.format ( "packet header must be 0x32 but is %02x", start ) );
    }

    final byte type = buffer.get ();
    logger.debug ( "Type: {}" );

    buffer.get (); // unknown
    buffer.get (); // unknown

    buffer.getUnsignedShort (); // request id

    final int plen = buffer.getUnsignedShort ();
    final int dlen = buffer.getUnsignedShort ();

    int errorInfo;
    if ( type == 2 || type == 3 )
    {
        errorInfo = buffer.getUnsignedShort ();
        logger.debug ( "Error info: {}", errorInfo );
    }
    else
    {
        errorInfo = 0;
    }

    final IoBuffer parameters = IoBuffer.allocate ( plen );
    final IoBuffer data = IoBuffer.allocate ( dlen );

    buffer.get ( parameters.array () );
    buffer.get ( data.array () );

    logger.debug ( "plen: {}, dlen: {}, remain: {}", new Object[] { plen, dlen, buffer.remaining () } );
    logger.debug ( "Parameters: {}", parameters );
    logger.debug ( "Data: {}", data );

    if ( parameters.remaining () == 2 && parameters.get ( 0 ) == (byte)4 )
    {
        // Data read reply
        return decodeDataReadReply ( parameters, data );
    }
    else if ( parameters.remaining () == 8 && parameters.get ( 0 ) == (byte)0xF0 )
    {
        // FIXME: better detection
        final int maxPDU = parameters.getUnsignedShort ( 6 );
        return new DaveConnectionEstablishedMessage ( maxPDU );
    }
    else
    {
        return new DaveGenericMessage ( parameters, data );
    }
}
 
Example 20
Source File: ITCHDeflateCodec.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

	boolean debugEnabled = logger.isDebugEnabled();

	if(debugEnabled) {

		logger.debug("Decode [limit: {}; remaining: {}; buffer:\n{}]", in.limit(), in.remaining(),
		        MINAUtil.getHexdumpAdv( in, in.remaining()));
	}

	in.mark();
	in.order(ByteOrder.LITTLE_ENDIAN);

	if (in.remaining() < HEADER_SIZE) {
		in.reset();
		return false;
	}

	byte[] actualDelimiter = new byte[DELIMITER_LENGTH];

	in.get(actualDelimiter);

	if(! Arrays.equals(delimiter, actualDelimiter)) {

           logger.error("Delimiter {} does not equeals to expected {}", actualDelimiter, delimiter);

	}

	int expectedDecompressedLength = in.getUnsignedShort();

	int chunkLength = in.getUnsignedShort();

	if (in.remaining() < chunkLength) {
		logger.debug("Received only part of bunch");
		in.reset();
		return false;
	}

	byte [] rawContent = new byte[(int)chunkLength];

	in.get(rawContent);

	byte[] decompressed = null;

	try {

		decompressed = decompress(rawContent);

	} catch (Exception e) {

		logger.error("Input could not be decompressed", e);
		return true;

	}

	if(debugEnabled) {

		logger.debug("Decompressed:\n{};", HexDumper.getHexdump(decompressed));

	}

	if(decompressed.length != expectedDecompressedLength) {
		logger.error("Lengs of the decompressed data {} is not equals to expected length {}",decompressed.length, expectedDecompressedLength);
	}

	IoBuffer buffer = IoBuffer.allocate(decompressed.length, false);

	buffer.put(decompressed);

	buffer.flip();

	out.write(buffer);

	return true;

}