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

The following examples show how to use org.apache.mina.core.buffer.IoBuffer#putLong() . 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: InternalJsonCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (message instanceof IMessage) {
        Map<String, Object> map = MessageUtil.convertToHashMap((IMessage)message);
        String json = objectMapper.writeValueAsString(map);

        long seq = sequence.getAndIncrement();

        IoBuffer buffer = IoBuffer.allocate(json.length() + HEADER_SIZE);
        buffer.putLong(json.length());
        buffer.putLong(seq);
        buffer.put(json.getBytes());

        out.write(buffer.flip());

        ((IMessage) message).getMetaData().setRawMessage(buffer.array());

        if (logger.isDebugEnabled()) {
            logger.debug("encode() sequnce {} as hex [{}]", seq, buffer.getHexDump());
        }
    } else {
        out.write(message);
    }
}
 
Example 2
Source File: TestITCHVisitorPositive.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testVariableLength() {
    IoBuffer buffer = IoBuffer.allocate(8);
    buffer.order(ByteOrder.nativeOrder());
    buffer.putLong(Long.MAX_VALUE);
    buffer.position(0);

    IMessage msg = new MapMessage("TEST", "result");
    ITCHVisitorDecode itchVisitorDecode = new ITCHVisitorDecode(buffer, ByteOrder.nativeOrder(), msg, DefaultMessageFactory.getFactory());

    Map<String, IAttributeStructure> attributes = new HashMap<>();
    attributes.put("Length", new AttributeStructure("Length", "8", 8, JavaType.JAVA_LANG_INTEGER));
    attributes.put("Type", new AttributeStructure("Type", "UIntXX", "UIntXX", JavaType.JAVA_LANG_INTEGER));

    IFieldStructure fieldStructure = new FieldStructure("", "", "", "", attributes,
            Collections.emptyMap(), JavaType.JAVA_MATH_BIG_DECIMAL, false, false, false, null);

    itchVisitorDecode.visit("test", BigDecimal.ZERO, fieldStructure, false);

    Assert.assertThat(msg.getField("test"), CoreMatchers.is(BigDecimal.valueOf(Long.MAX_VALUE)));
}
 
Example 3
Source File: AbstractSourceType.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void render ( final IoBuffer buffer, final int offset, final DataItemValue value )
{
    final IoBuffer slice = buffer.getSlice ( offset, this.length );
    logger.trace ( "After Slice: {}", buffer );

    if ( value != null )
    {
        slice.put ( makeValidState ( value ) );
        slice.put ( makeState ( value ) );
        slice.putLong ( makeTimestamp ( value.getTimestamp () ) );
        putValue ( slice, value.getValue () );
    }
    else
    {
        slice.put ( (byte)0xFF ); // invalid
        slice.put ( makeState ( null ) );
        slice.putLong ( makeTimestamp ( null ) );
        putValue ( slice, null );
    }

    logger.trace ( "Buffer: {}", buffer );
}
 
Example 4
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void encodeLongCollection ( final IoBuffer buffer, final byte fieldNumber, final Collection<Long> data ) throws Exception
{
    buffer.put ( fieldNumber );
    if ( data != null )
    {
        buffer.put ( TYPE_LONG_LIST );
        buffer.putInt ( data.size () );
        for ( final Long entry : data )
        {
            buffer.putLong ( entry );
        }
    }
    else
    {
        buffer.put ( TYPE_NULL );
    }
}
 
Example 5
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
public static IoBuffer toIobuffer(final MassMessage message) {
	IoBuffer buf = IoBuffer.allocate(8 + message.getLength());
	buf.putInt(message.getLength() + 4); // 总长度
	buf.putInt(message.getBuffLength()); // 内容长度
	buf.put(message.getBuffer());
	for (Long target : message.getTargets()) {
		buf.putLong(target);
	}
	buf.rewind();
	return buf;
}
 
Example 6
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 转换为发送的iobuff
 *
 * @param message
 * @param id
 * @return 【length|msgid|data】
 */
   public static IoBuffer toIobufferWithID(final Message message, long id) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	int msgDataLength = msgData.length;
	IoBuffer buf = IoBuffer.allocate(16 + msgDataLength);
	buf.putInt(msgDataLength + 12);
	buf.putLong(id);
	buf.putInt(msgID);
	buf.put(msgData);
	buf.rewind();
	return buf;
}
 
Example 7
Source File: ArduinoCodec.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void encodeWriteRequest ( final IoBuffer data, final WriteRequestMessage message )
{
    data.putShort ( message.getIndex () );
    final Object value = message.getData ();
    if ( value == null )
    {
        data.put ( (byte)0x00 );
    }
    else if ( value instanceof Boolean )
    {
        data.put ( (byte)0x01 );
        data.put ( (byte) ( (Boolean)value ? 0xFF : 0x00 ) );
    }
    else if ( value instanceof Float || value instanceof Double )
    {
        data.put ( (byte)0x04 );
        data.putFloat ( ( (Number)value ).floatValue () );
    }
    else if ( value instanceof Long )
    {
        data.put ( (byte)0x03 );
        data.putLong ( ( (Number)value ).longValue () );
    }
    else if ( value instanceof Number )
    {
        data.put ( (byte)0x02 );
        data.putInt ( ( (Number)value ).intValue () );
    }
    else if ( value instanceof String )
    {
        data.put ( (byte)0x02 );
        data.putInt ( Integer.parseInt ( (String)value ) );
    }
    else
    {
        throw new RuntimeException ( String.format ( "Unable to write request of type %s", value.getClass () ) );
    }
}
 
Example 8
Source File: ProtocolEncoderImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void encodeEntry ( final IoSession session, final IoBuffer data, final Entry entry ) throws ProtocolCodecException
{
    data.putUnsignedShort ( entry.getRegister () );
    data.put ( entry.getMissedUpdates () );
    data.putLong ( entry.getTimestamp () );
    data.putEnumSetShort ( entry.getStates () );

    // put payload
    encodeVariant ( session, data, entry.getValue () );
}
 
Example 9
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encodeLong ( final IoBuffer buffer, final byte fieldNumber, final Long data ) throws Exception
{
    buffer.put ( fieldNumber );
    if ( data != null )
    {
        buffer.put ( TYPE_LONG );
        buffer.putLong ( data );
    }
    else
    {
        buffer.put ( TYPE_NULL );
    }
}
 
Example 10
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encodePrimitiveLong ( final IoBuffer buffer, final byte fieldNumber, final long data ) throws Exception
{
    buffer.put ( fieldNumber );
    buffer.put ( TYPE_LONG );
    buffer.putLong ( data );
}
 
Example 11
Source File: DefaultBinaryContext.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void inlineEncodeVariant ( final IoBuffer buffer, final Variant variant ) throws Exception
{
    final VariantType type = variant.getType ();
    buffer.putEnum ( type );

    switch ( type )
    {
        case BOOLEAN:
            buffer.put ( variant.asBoolean () ? (byte)0xFF : (byte)0x00 );
            break;
        case DOUBLE:
            buffer.putDouble ( variant.asDouble () );
            break;
        case INT32:
            buffer.putInt ( variant.asInteger () );
            break;
        case INT64:
            buffer.putLong ( variant.asLong () );
            break;
        case STRING:
            buffer.putPrefixedString ( variant.asString (), STRING_PREFIX_LEN, this.encoder );
            break;
        case NULL:
            break;
        case UNKNOWN:
            break;
    }
}
 
Example 12
Source File: LongFieldTypeHandler.java    From CXTouch with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void encode(Long value, IoBuffer outBuffer) {
    long val = value;
    outBuffer.put(getType());
    outBuffer.putLong(val);
}
 
Example 13
Source File: TestInternalJsonCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecoder() throws Exception {
    IoBuffer buffer = IoBuffer.allocate(1024);

    ProtocolDecoderOutput decoderOutput = Mockito.mock(ProtocolDecoderOutput.class);
    Mockito.doAnswer(new Answer<Void>() {

        private final String[] responses = { "Cause=Unexpected end-of-input within/between Object entries",
                "Qty=123.123|ClOrdID=|MessageType=123", "Qty=456.456|ClOrdID=ORD34|MessageType=100",
                "Qty=777.777|ClOrdID=WithDate|fieldDate=2010-01-01T11:22:33.444555666|MessageType=123"
        };
        private int index;

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            String input = invocation.<IMessage>getArgument(0).toString();
            Assert.assertTrue("index: " + index + " expect: " + responses[index] + " actual: " + input, input.startsWith(responses[index]));
            index++;
            return null;
        }
    }).when(decoderOutput).write(Mockito.anyObject());

    String data = "{\"Qty\":123.123,\"ClOrdID\"";
    buffer.putLong(data.length());
    buffer.putLong(1L);
    buffer.put(data.getBytes());

    data = "{\"Qty\":123.123,\"ClOrdID\":\"\",\"MessageType\":123}";
    buffer.putLong(data.length());
    buffer.putLong(2L);
    buffer.put(data.getBytes());

    data = "{\"Qty\":456.456,\"ClOrdID\":\"ORD34\",\"MessageType\":100}";
    buffer.putLong(data.length());
    buffer.putLong(3L);
    buffer.put(data.getBytes());

    data = "{\"Qty\":777.777,\"ClOrdID\":\"WithDate\",\"fieldDate\":[\"java.time.LocalDateTime\",\"2010-01-01T11:22:33.444555666\"],\"MessageType\":123}";
    buffer.putLong(data.length());
    buffer.putLong(4L);
    buffer.put(data.getBytes());
    buffer.flip();

    codec.decode(session, buffer, decoderOutput);
}
 
Example 14
Source File: ProtocolEncoderImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private void encodeVariant ( final IoSession session, final IoBuffer data, final Variant value ) throws ProtocolCodecException
{
    if ( value == null )
    {
        data.put ( DataType.DEAD.getDataType () ); // dead
    }
    else if ( value.isNull () )
    {
        data.put ( DataType.NULL.getDataType () );
    }
    else if ( value.isBoolean () )
    {
        data.put ( DataType.BOOLEAN.getDataType () );
        data.put ( (byte) ( value.asBoolean () ? 0xFF : 0x00 ) );
    }
    else if ( value.isInteger () )
    {
        data.put ( DataType.INT32.getDataType () );
        data.putInt ( value.asInteger ( null ) );
    }
    else if ( value.isLong () )
    {
        data.put ( DataType.INT64.getDataType () );
        data.putLong ( value.asLong ( null ) );
    }
    else if ( value.isDouble () )
    {
        data.put ( DataType.DOUBLE.getDataType () );
        data.putDouble ( value.asDouble ( null ) );
    }
    else if ( value.isString () )
    {
        data.put ( DataType.STRING.getDataType () );
        try
        {
            data.putPrefixedString ( value.asString ( null ), Sessions.getCharsetEncoder ( session ) );
        }
        catch ( final CharacterCodingException e )
        {
            throw new ProtocolCodecException ( e );
        }
    }
}
 
Example 15
Source File: Int64Accessor.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void put ( final IoBuffer data, final Long value )
{
    data.putLong ( value );
}
 
Example 16
Source File: WebSocketEncoder.java    From red5-websocket with Apache License 2.0 4 votes vote down vote up
public static IoBuffer encodeOutgoingData(Packet packet) {
    log.debug("encode outgoing: {}", packet);
    // get the payload data
    IoBuffer data = packet.getData();
    // get the frame length based on the byte count
    int frameLen = data.limit();
    // start with frame length + 2b (header info)
    IoBuffer buffer = IoBuffer.allocate(frameLen + 2, false);
    buffer.setAutoExpand(true);
    // set the proper flags / opcode for the data
    byte frameInfo = (byte) (1 << 7);
    switch (packet.getType()) {
        case TEXT:
            if (log.isTraceEnabled()) {
                log.trace("Encoding text frame  \r\n{}", new String(packet.getData().array()));
            }
            frameInfo = (byte) (frameInfo | 1);
            break;
        case BINARY:
            log.trace("Encoding binary frame");
            frameInfo = (byte) (frameInfo | 2);
            break;
        case CLOSE:
            frameInfo = (byte) (frameInfo | 8);
            break;
        case CONTINUATION:
            frameInfo = (byte) (frameInfo | 0);
            break;
        case PING:
            log.trace("ping out");
            frameInfo = (byte) (frameInfo | 9);
            break;
        case PONG:
            log.trace("pong out");
            frameInfo = (byte) (frameInfo | 0xa);
            break;
        default:
            break;
    }
    buffer.put(frameInfo);
    // set the frame length
    log.trace("Frame length {} ", frameLen);
    if (frameLen <= 125) {
        buffer.put((byte) ((byte) frameLen & (byte) 0x7F));
    } else if (frameLen > 125 && frameLen <= 65535) {
        buffer.put((byte) ((byte) 126 & (byte) 0x7F));
        buffer.putShort((short) frameLen);
    } else {
        buffer.put((byte) ((byte) 127 & (byte) 0x7F));
        buffer.putLong((int) frameLen);
    }
    buffer.put(data);
    buffer.flip();
    if (log.isTraceEnabled()) {
        log.trace("Encoded: {}", buffer);
    }
    return buffer;
}