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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#getLong() . 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: 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 2
Source File: LongFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Long decode(IoBuffer inBuffer) {
    if (inBuffer.remaining() < 8) {
        return null;
    } else {
        return inBuffer.getLong();
    }
}
 
Example 3
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 4
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Long decodeLong ( final IoBuffer buffer ) throws Exception
{
    final byte type = checkType ( buffer, TYPE_LONG, true );

    if ( type == TYPE_NULL )
    {
        return null;
    }
    else
    {
        return buffer.getLong ();
    }
}
 
Example 5
Source File: InternalJsonCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    boolean decoded = false;

    while (in.remaining() > HEADER_SIZE) {
        in.mark();
        long length = in.getLong();
        long seq = in.getLong();

        if (in.remaining() >= length) {
            byte[] buff = new byte[(int) length];
            in.get(buff);

            if (logger.isDebugEnabled()) {
                logger.debug("decode() sequnce {} as hex [{}]", seq, Hex.encodeHex(buff));
            }
            decoded = true;

            in.reset();
            byte[] rawData = new byte[(int) length + HEADER_SIZE];
            in.get(rawData);

            IMessage message = null;

            try {
                Map<?, ?> map = objectMapper.readValue(buff, HashMap.class);
                message = MessageUtil.convertToIMessage(map, msgFactory, TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE,
                        TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE);

            } catch (Exception e) {
                message = msgFactory.createMessage("Exception",
                        TCPIPMessageHelper.INCOMING_MESSAGE_NAME_AND_NAMESPACE);

                message.addField("Cause", e.getMessage());
            }

            message.getMetaData().setRawMessage(rawData);
            out.write(message);
        } else {
            in.reset();
        }
    }

    return decoded;
}
 
Example 6
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 7
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 8
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public long decodePrimitiveLong ( final IoBuffer buffer ) throws Exception
{
    checkType ( buffer, TYPE_LONG, false );
    return buffer.getLong ();
}
 
Example 9
Source File: Int64Accessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Long get ( final IoBuffer data, final int index )
{
    return data.getLong ( index );
}
 
Example 10
Source File: WebMessageDecoder.java    From cim with Apache License 2.0 4 votes vote down vote up
@Override
public void decode(IoSession iosession, IoBuffer in, ProtocolDecoderOutput out) throws InvalidProtocolBufferException{
	
	/*
	 * 判断是否是握手请求
	 */

	if(isHandShakeRequest(iosession,in)) {
		handleHandshake(iosession,in, out);
		return;
	}

	
	in.mark();
	
	/*
	 * 接下来判断fin标志位是否是1 如果是0 则等待消息接收完成
	 */
	byte tag = in.get();
	int frameFin = tag  > 0 ?  0 : 1;
	if(frameFin == 0) {
		in.reset();
		return;
	}
	
	/*
	 * 获取帧类型,因为使用了protobuf,所以只支持二进制帧 OPCODE_BINARY,以及客户端关闭连接帧通知 OPCODE_CLOSE
	 */
	int frameCode = tag & TAG_MASK;
	
	if(OPCODE_BINARY == frameCode) {
		
		byte head = in.get();
		byte dataLength = (byte) (head & PAYLOADLEN);
		int realLength;
		
		/*
		 *Payload len,7位或者7+16位或者7+64位,表示数据帧中数据大小,这里有好几种情况。
		 *如果值为0-125,那么该值就是payload data的真实长度。
		 *如果值为126,那么该7位后面紧跟着的2个字节就是payload data的真实长度。
		 *如果值为127,那么该7位后面紧跟着的8个字节就是payload data的真实长度。
		 */
		if (dataLength == HAS_EXTEND_DATA) {
			realLength = in.getShort();
		} else if (dataLength == HAS_EXTEND_DATA_CONTINUE) {
			realLength = (int) in.getLong();
		}else {
			realLength = dataLength;
		}

		boolean masked = (head >> 7 & MASK) == 1;
		if (masked) {
			byte[] mask = new byte[4];
			in.get(mask);
			
			byte[] data = new byte[realLength];
			in.get(data);
			for (int i = 0; i < realLength; i++) {
				data[i] = (byte) (data[i] ^ mask[i % 4]);
			}
			
			handleMessage(data,out);
		}
		
	}else if(OPCODE_CLOSE == frameCode) {
       	handleClose(iosession,in);
	}else {
		in.get(new byte[in.remaining()]);
	}

}