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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#order() . 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: 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 2
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private Object decodeData ( final IoBuffer data ) throws ProtocolCodecException
{
    data.order ( ByteOrder.LITTLE_ENDIAN );

    final byte dataType = data.get ();
    switch ( dataType )
    {
        case 0:
            return null;
        case 1:
            return data.get () != 0x00;
        case 2:
            return data.getInt ();
        case 3:
            return data.getLong ();
        case 4:
            return data.getFloat ();
        default:
            throw new ProtocolCodecException ( String.format ( "Data type %02x is unknown", dataType ) );
    }

}
 
Example 3
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void encode ( final IoSession session, final Object message, final ProtocolEncoderOutput output ) throws Exception
{
    final IoBuffer data = IoBuffer.allocate ( 0 );
    data.order ( ByteOrder.LITTLE_ENDIAN );
    data.setAutoExpand ( true );

    if ( message instanceof WriteRequestMessage )
    {
        encodeHeader ( data, (CommonMessage)message );
        encodeWriteRequest ( data, (WriteRequestMessage)message );
    }
    else if ( message instanceof CommonMessage )
    {
        encodeHeader ( data, (CommonMessage)message );
    }
    data.flip ();
    output.write ( data );
}
 
Example 4
Source File: ModbusProtocol.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Encode the data from Java byte order to requested modbus byte order
 *
 * @param data
 *            the data to encode
 * @param dataOrder
 *            the target modbus byte order
 * @return the converted data, or the input data if no conversion was
 *         necessary
 */
public static IoBuffer convertData ( final IoBuffer data, final ByteOrder dataOrder )
{
    if ( dataOrder == ByteOrder.BIG_ENDIAN )
    {
        return data;
    }

    final IoBuffer result = IoBuffer.allocate ( data.capacity () );
    result.order ( dataOrder );

    for ( int i = 0; i < data.remaining () / 2; i++ )
    {
        // convert to LITTLE_ENDIAN
        result.putUnsignedShort ( data.getUnsignedShort ( i * 2 ) );
    }

    // the byte order we use is BIG_ENDIAN
    result.order ( ByteOrder.BIG_ENDIAN );

    return result;
}
 
Example 5
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 6
Source File: TestNTGCodecPositive.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private void decodeBytes(int[] ints) throws Exception{
	byte[] bytes = new byte[ints.length];
	for (int i =0; i<ints.length; i++)
	{
		bytes[i] = (byte) ints[i];
	}

       NTGCodec decodeCodec2 = new NTGCodec();
       decodeCodec2.init(serviceContext, null, DefaultMessageFactory.getFactory(), TestNTGHelper.getDictionary());
	ProtocolDecoderOutput decoderOutput2 = new MockProtocolDecoderOutput();

	IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
	toDecode.setAutoExpand(true);
	toDecode.put(bytes);
	//IoBuffer.wrap( Arrays.copyOf(((IoBuffer)lastMessage).array(), ((IoBuffer)lastMessage).limit() ));
	toDecode.compact();
	toDecode.order(ByteOrder.LITTLE_ENDIAN);

	IoSession decodeSession2 = new DummySession();
	boolean decodableResult = decodeCodec2.decodable( decodeSession2, toDecode );
	Assert.assertTrue( "Test for decoding error.", decodableResult);
	decoderOutput2 = new MockProtocolDecoderOutput();

	boolean decodeResult = decodeCodec2.doDecode( decodeSession2, toDecode, decoderOutput2 );
	Assert.assertTrue( "Decoding error.", decodeResult );

       Assert.assertTrue("Message queue size must not less then 1.", ((AbstractProtocolDecoderOutput)decoderOutput2).getMessageQueue().size() >= 1);
	Object decodedMessage2 = ((AbstractProtocolDecoderOutput)decoderOutput2).getMessageQueue().element();

	Assert.assertTrue( "Object must be instance of IMessage.", decodedMessage2 instanceof IMessage);
	Assert.assertTrue( "Object must be instance of MapMessage.", decodedMessage2 instanceof MapMessage);
}
 
Example 7
Source File: CumulativeProtocolDecoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void storeRemainingInSession(IoBuffer buf, IoSession session) {
    final IoBuffer remainingBuf = IoBuffer.allocate(buf.capacity()).setAutoExpand(true);

    remainingBuf.order(buf.order());
    remainingBuf.put(buf);

    session.setAttribute(BUFFER, remainingBuf);
}
 
Example 8
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecodeMessage() throws Exception
{
	FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE);
	int[] array = {
			0xA8, 0xC0, 0x81, 0xB0, 0x32, 0x30, 0x31, 0x32,
			0x30, 0x31, 0X30, 0X31, 0x2D, 0x30, 0x31, 0x3A,
			0x30, 0x31, 0x3A, 0x30, 0x31, 0x2E, 0x33, 0x33,
			0xB3, 0xB0, 0x80, 0x4D, 0x41, 0x44, 0x54, 0x59,
			0xB0, 0x74, 0x6E, 0x70, 0x31, 0x32, 0xB3, 0x80,
			0x80};
	byte[] b = new byte[array.length];
	for (int i=0; i<array.length; i++)
	{
		b[i] = (byte) array[i];
	}

	IoBuffer toDecode = IoBuffer.wrap( b );
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();

	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	boolean decodableResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
	System.out.println(decoderOutput.getMessageQueue().element());

	Assert.assertTrue( "Decoding error.", decodableResult);
}
 
Example 9
Source File: MinaDecoder.java    From grain with MIT License 5 votes vote down vote up
private void storeRemainingInSession(IoBuffer buf, IoSession session) {
	IoBuffer remainingBuf = IoBuffer.allocate(buf.capacity());
	remainingBuf.setAutoExpand(true);
	remainingBuf.order(buf.order());
	remainingBuf.put(buf);
	session.setAttribute(BUFFER, remainingBuf);
}
 
Example 10
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 11
Source File: TestITCHCodecPositive.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
/**
 * Try to decode SymbolDirectory from byte[] and print result message into console.
 */
@Ignore@Test
public void testDecodeMessageSymbolDirectory(){
       ITCHCodec codec = (ITCHCodec) getMessageHelper().getCodec(serviceContext);
	int[] array = {
			0x64, 0x00, // Size
			0x01,       // Count
			0x31,       // MD Group
			0x00, 0x00, 0x00, 0x00, // SeqNumber
			0x5C, 0x52, 0xF0, 0x9D, 0xE6, 0x2B, 0xA4, 0x42, 0x0F, 0x00, 0x00, 0x00, 0x20, 0x49, 0x54, 0x31, 0x30, 0x30, 0x31, 0x30, 0x30, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x41, 0x48, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x45, 0x55, 0x52, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x01, 0x31, 0x00, 0x00, 0x00, 0x00, 0x5C, 0x52, 0xF8, 0xE9, 0xE7, 0x2B, 0xA9, 0x42, 0x0F, 0x00, 0x00, 0x00, 0x20, 0x49, 0x54, 0x30, 0x30, 0x30, 0x30, 0x30, 0x36, 0x32, 0x30, 0x37, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x41, 0x48, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x45, 0x55, 0x52, 0x00, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x47, 0x45, 0x4E, 0x45, 0x52, 0x41, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00};
	byte[] b = new byte[array.length];
	for (int i=0; i<array.length; i++)
	{
		b[i] = (byte) array[i];
	}

	IoBuffer toDecode = IoBuffer.wrap( b );
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();
	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	try{
		boolean decodableResult = codec.doDecode( decodeSession, toDecode, decoderOutput );
		System.out.println((IMessage) decoderOutput.getMessageQueue().element());
		Assert.assertTrue( "Decoding error.", decodableResult);
		System.out.println("position = "+toDecode.position());
	}catch(Exception e){
		logger.error(e.getMessage(),e);
		Assert.fail(e.getMessage());
	}

}
 
Example 12
Source File: TestNTGCodecPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private void testRoundTrip(IMessage message, IDictionaryStructure dictionary) {
	try
	{
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());

		Assert.assertNotNull("Message structure is null.", msgStruct);

           NTGCodec encodeCodec = new NTGCodec();

		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);

           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
			encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			AbstractProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();

			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			//IoBuffer.wrap( Arrays.copyOf(((IoBuffer)lastMessage).array(), ((IoBuffer)lastMessage).limit() ));
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			boolean decodableResult = decodeCodec.decodable(decodeSession, toDecode);
			decoderOutput = new MockProtocolDecoderOutput();

			Assert.assertTrue("Test for decoding error.", decodableResult);

			boolean decodeResult = decodeCodec.doDecode(decodeSession, toDecode, decoderOutput);
			Assert.assertTrue("Decoding error.", decodeResult);

               Assert.assertTrue("Message queue size must not less then 1.", decoderOutput.getMessageQueue().size() >= 1);
			Object decodedMessage = decoderOutput.getMessageQueue().element();

			Assert.assertTrue( "Object must be instance of IMessage.", decodedMessage instanceof IMessage);
			Assert.assertTrue( "Object must be instance of MapMessage.", decodedMessage instanceof MapMessage);
               Assert.assertTrue("Messages must be equal. Original message:" + JsonMessageConverter.toJson(message, dictionary) + "; "
                       + "result message:" + JsonMessageConverter.toJson((IMessage)decodedMessage, dictionary),
                       message.compare((MapMessage) decodedMessage));
		}
	}
	catch (Exception e)
	{
	    logger.error(e.getMessage(), e);
		Assert.fail(ErrorUtil.formatException(e));
	}
}
 
Example 13
Source File: NTGCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public boolean decodable(IoSession session, IoBuffer inputBuffer)
{
	inputBuffer.order(ByteOrder.LITTLE_ENDIAN);

       boolean isDecodable = false;

       if(inputBuffer.remaining() < MINIMAL_CAPACITY) {
		return false;
	}

	inputBuffer.order(ByteOrder.LITTLE_ENDIAN);
	inputBuffer.mark();
	byte messageStartByte  = inputBuffer.get();

	// Implementation of SEVRER_START_OF_MESSAGE_INDICATOR need to be qualified.
       if(messageStartByte != CLIENT_START_OF_MESSAGE_INDICATOR
	/* && SEVRER_START_OF_MESSAGE_INDICATOR != messageStartByte */ )
	{
           inputBuffer.reset();

           logger.error("Unexpected start of message: {} (expected: {})", messageStartByte, CLIENT_START_OF_MESSAGE_INDICATOR);
           logger.error("Buffer hexdump:{}{}", System.lineSeparator(), HexDumper.getHexdump(inputBuffer, inputBuffer.remaining()));

           throw new EPSCommonException("Unexpected start of message: " + messageStartByte);
	}

       short messageLength = inputBuffer.getShort();

	if( messageLength < 0 )
	{
		throw new EPSCommonException( "Message length cannot be negative." );
	}

	if( inputBuffer.remaining() >= messageLength )
	{
		isDecodable = true;
	}

       byte messageType = inputBuffer.get();
	inputBuffer.reset();

	if(logger.isDebugEnabled())
	{
		messageLength += messageLength == 0 ? 0 : 3;
		logger.debug("decodable() result [{}].", isDecodable);
		logger.debug("decodable() message length [{}], message type [{}]", messageLength, messageType);
           //logger.debug( String.format(" decodable() as hex    [%s]", NTGUtility.getHexdump( inputBuffer, messageLength )));
		inputBuffer.reset();
		logger.debug(MINAUtil.getHexdumpAdv(inputBuffer, messageLength));
		inputBuffer.reset();
	}
	return isDecodable;
}
 
Example 14
Source File: ITCHVisitorDecode.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public ITCHVisitorDecode(IoBuffer buffer, ByteOrder byteOrder, IMessage msg, IMessageFactory msgFactory) {
	this.buffer = buffer.order(byteOrder);
	this.byteOrder = byteOrder;
	this.msg = msg;
	this.msgFactory = msgFactory;
}
 
Example 15
Source File: TestNTGCodecNegative.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Negative test encode Heartbeat message with StartOfMessage=3 and decode it after
 */
@Test
public void testWrongMessage(){
       IMessage message = DefaultMessageFactory.getFactory().createMessage("Heartbeat", "NTG");
       IMessage messageHeader = DefaultMessageFactory.getFactory().createMessage("MessageHeader", "NTG");
	messageHeader.addField("StartOfMessage", 3);
	messageHeader.addField("MessageLength", 9);
	messageHeader.addField("MessageType", "2");
	message.addField("MessageHeader", messageHeader);
	try{
           IDictionaryStructure dictionary = TestNTGHelper.getDictionary();
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());
		Assert.assertNotNull("Message structure is null.", msgStruct);
           NTGCodec encodeCodec = new NTGCodec();
		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
 		encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			decodeCodec.decodable(decodeSession, toDecode);
			Assert.fail("Exception hasn't been thrown");
		}
	}catch(Exception e){
		Assert.assertEquals("Unexpected start of message: 3", e.getMessage());
	}

}
 
Example 16
Source File: TestNTGVisitorPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test case Integer data type
 */
@Test
   public void testNTGVisitorEncode_IntegerField()
{
	Integer value = Integer.MAX_VALUE;
	int offset = 0 ;
	int length = 4;
	String fldName = "FieldInteger";
       String fldNamespace = "NTG";
	String fldDescr = "Description " + fldName;

	Map<String, IAttributeStructure> protocolAttributes = new HashMap<>();

       protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure(
               NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER));

       protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure(
               NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(),
			JavaType.JAVA_LANG_STRING));

       protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure(
               NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER));

	IFieldStructure mockSimpleField =
			new FieldStructure(fldName, fldNamespace, fldDescr, null,
					protocolAttributes, null, JavaType.JAVA_LANG_INTEGER, false, false, false, null);

	ByteBuffer bb = ByteBuffer.wrap(new byte[length]);
	bb.order( ByteOrder.LITTLE_ENDIAN);
	bb.putInt(value);

	try
	{
		IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace,
				fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_INTEGER,
				true, false, false, value.toString()) ;

           NTGVisitorEncode visitor = new NTGVisitorEncode();
           visitor.visit(mockSimpleField.getName(), value, fldStruct, false);
           IoBuffer ioBuffer = visitor.getBuffer();

		for( int i = 0 ; i < bb.array().length; i++ )
		{
			logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i,
					bb.array()[i], ioBuffer.array()[i]);

               Assert.assertEquals(String.format("NTGVisitor.visit(Integer) failed. " +
					"Error at index [%d]. Expected [%x], actual [%x].", i,
					bb.array()[i], ioBuffer.array()[i]),
					bb.array()[i], ioBuffer.array()[i]);
		}

		IoBuffer copy = ioBuffer.duplicate();
		copy.order(ByteOrder.LITTLE_ENDIAN);
		copy.flip();
		Integer restored = copy.getInt();

		Assert.assertEquals( value, restored );

           logger.info("Visitor: method visit(Integer)  PASSED.");
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		logger.error(ex.getMessage(),ex);
		Assert.fail(ex.getMessage());
	}
}
 
Example 17
Source File: TestNTGVisitorPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test case Long data type
 */
@Test
   public void testNTGVisitorEncode_LongField()
{
	Long value = Long.MAX_VALUE;
	int offset = 0 ;
	int length = 8;
	String fldName = "FieldLong";
       String fldNamespace = "NTG";
	String fldDescr = "Description " + fldName;

	Map<String, IAttributeStructure> protocolAttributes = new HashMap<>();

       protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure(
               NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER));

       protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure(
               NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(),
			JavaType.JAVA_LANG_STRING));

       protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure(
               NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER));

	IFieldStructure mockSimpleField =
			new FieldStructure(fldName, fldNamespace, fldDescr, null,
					protocolAttributes, null, JavaType.JAVA_LANG_LONG, false, false, false, null);

	ByteBuffer bb = ByteBuffer.wrap(new byte[length]);
	bb.order( ByteOrder.LITTLE_ENDIAN);
	bb.putLong(value);

	try
	{
		IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace,
				fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_LONG,
				true, false, false, value.toString()) ;

           NTGVisitorEncode visitor = new NTGVisitorEncode();
           visitor.visit(mockSimpleField.getName(), value, fldStruct, false);
           IoBuffer ioBuffer = visitor.getBuffer();

		for( int i = 0 ; i < bb.array().length; i++ )
		{
			logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i,
					bb.array()[i], ioBuffer.array()[i]);

               Assert.assertEquals(String.format("NTGVisitor.visit(Long) failed. " +
					"Error at index [%d]. Expected [%x], actual [%x].", i,
					bb.array()[i], ioBuffer.array()[i]),
					bb.array()[i], ioBuffer.array()[i]);
		}

		IoBuffer copy = ioBuffer.duplicate();
		copy.order(ByteOrder.LITTLE_ENDIAN);
		copy.flip();
		Long restored = copy.getLong();

		Assert.assertEquals( value, restored );

           logger.info("Visitor: method visit(Long)  PASSED.");
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		logger.error(ex.getMessage(),ex);
		Assert.fail(ex.getMessage());
	}
}
 
Example 18
Source File: TestNTGVisitorPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test case Double data type
 */
@Test
   public void testNTGVisitorEncode_DoubleField()
{
	Double value = (double) (Integer.MAX_VALUE/10000);
	int offset = 0 ;
	int length = 8;
	String fldName = "FieldDouble";
       String fldNamespace = "NTG";
	String fldDescr = "Description " + fldName;

	Map<String, IAttributeStructure> protocolAttributes = new HashMap<>();

       protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure(
               NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER));

       protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure(
               NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(),
			JavaType.JAVA_LANG_STRING));

       protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure(
               NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER));

	IFieldStructure mockSimpleField =
			new FieldStructure(fldName, fldNamespace, fldDescr, null,
					protocolAttributes, null, JavaType.JAVA_LANG_DOUBLE, false, false, false, null);

	ByteBuffer bb = ByteBuffer.wrap(new byte[length]);
	bb.order( ByteOrder.LITTLE_ENDIAN);

	BigDecimal baseValue = new BigDecimal( value );
	BigDecimal baseScaled  = baseValue.setScale( 8, BigDecimal.ROUND_HALF_UP );
	BigDecimal multiplied = baseScaled.multiply( new BigDecimal(Math.pow(10, 8))) ;
	bb.putLong(multiplied.longValue());

	try
	{
		IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace,
				fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_DOUBLE,
				true, false, false, value.toString()) ;

           NTGVisitorEncode visitor = new NTGVisitorEncode();
           visitor.visit(mockSimpleField.getName(), value, fldStruct, false);
           IoBuffer ioBuffer = visitor.getBuffer();

		for( int i = 0 ; i < bb.array().length; i++ )
		{
			logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i,
					bb.array()[i], ioBuffer.array()[i]);

               Assert.assertEquals(String.format("NTGVisitor.visit(Double) failed. " +
					"Error at index [%d]. Expected [%x], actual [%x].", i,
					bb.array()[i], ioBuffer.array()[i]),
					bb.array()[i], ioBuffer.array()[i]);
		}
		IoBuffer copy = ioBuffer.duplicate();
		copy.order(ByteOrder.LITTLE_ENDIAN);
		copy.flip();
		Double restored = copy.getLong() /Math.pow(10, 8);

		Assert.assertEquals( value, restored );

           logger.info("Visitor: method visit(Double)  PASSED.");
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		logger.error(ex.getMessage(),ex);
		Assert.fail(ex.getMessage());
	}
}
 
Example 19
Source File: TestNTGVisitorPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Test case Float data type
 */
   @Test
   public void testNTGVisitorEncode_FloatField()
{
	Float value = (float) (Integer.MAX_VALUE/10000);
	int offset = 0 ;
	int length = 4;
	String fldName = "FieldFloat";
       String fldNamespace = "NTG";
	String fldDescr = "Description " + fldName;

	Map<String, IAttributeStructure> protocolAttributes = new HashMap<>();

       protocolAttributes.put(NTGProtocolAttribute.Offset.toString(), new AttributeStructure(
               NTGProtocolAttribute.Offset.toString(), Integer.toString(offset), offset, JavaType.JAVA_LANG_INTEGER));

       protocolAttributes.put(NTGProtocolAttribute.Format.toString(), new AttributeStructure(
               NTGProtocolAttribute.Format.toString(), NTGFieldFormat.S.toString(), NTGFieldFormat.S.toString(),
			JavaType.JAVA_LANG_STRING));

       protocolAttributes.put(NTGProtocolAttribute.Length.toString(), new AttributeStructure(
               NTGProtocolAttribute.Length.toString(), Integer.toString(length), length, JavaType.JAVA_LANG_INTEGER));

	IFieldStructure mockSimpleField =
			new FieldStructure(fldName, fldNamespace, fldDescr, null,
					protocolAttributes, null, JavaType.JAVA_LANG_FLOAT, false, false, false, null);

	ByteBuffer bb = ByteBuffer.wrap(new byte[length]);
	bb.order( ByteOrder.LITTLE_ENDIAN);


	BigDecimal baseValue = new BigDecimal( value );
	BigDecimal baseScaled  = baseValue.setScale( 4, BigDecimal.ROUND_HALF_UP );
	BigDecimal multiplied = baseScaled.multiply( new BigDecimal(10000.0f)) ;
	bb.putInt(multiplied.intValue());


	try
	{
		IFieldStructure fldStruct = new FieldStructure(fldName, fldNamespace,
				fldDescr, null, protocolAttributes, null, JavaType.JAVA_LANG_FLOAT,
				true, false, false, value.toString()) ;

           NTGVisitorEncode visitor = new NTGVisitorEncode();
           visitor.visit(mockSimpleField.getName(), value, fldStruct, false);
           IoBuffer ioBuffer = visitor.getBuffer();

		for( int i = 0 ; i < bb.array().length; i++ )
		{
			logger.trace("Symbol at index [{}]. Expected [{}], actual [{}].", i,
					bb.array()[i], ioBuffer.array()[i]);

               Assert.assertEquals(String.format("NTGVisitor.visit(Float) failed. " +
					"Error at index [%d]. Expected [%x], actual [%x].", i,
					bb.array()[i], ioBuffer.array()[i]),
					bb.array()[i], ioBuffer.array()[i]);
		}

		IoBuffer copy = ioBuffer.duplicate();
		copy.order(ByteOrder.LITTLE_ENDIAN);
		copy.flip();
		Float restored = (float) copy.getInt() / 10000;

		Assert.assertEquals( value, restored );

           logger.info("Visitor: method visit(Float)  PASSED.");
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		logger.error(ex.getMessage(),ex);
		Assert.fail(ex.getMessage());
	}
}
 
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;

}