Java Code Examples for io.netty.buffer.ByteBuf#order()

The following examples show how to use io.netty.buffer.ByteBuf#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: ZclDataUtil.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static long readBits(ByteBuf input, int bytes) throws IOException {
   long result = 0;
   if (input.order() == ByteOrder.LITTLE_ENDIAN) {
      long shift = 0;
      for (int i = 0; i < bytes; ++i) {
         result = result | ((input.readByte() & 0xFFL) << shift);
         shift += 8;
      }
   } else {
      for (int i = 0; i < bytes; ++i) {
         result = (result << 8) | (input.readByte() & 0xFFL);
      }
   }

   return result;
}
 
Example 2
Source File: LengthFieldBasedFrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 * decode the length field encoded differently.  Note that this method must not modify the state of the specified
 * buffer (e.g. {@code readerIndex}, {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException if failed to decode the specified region
 */
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    long frameLength;
    switch (length) {
    case 1:
        frameLength = buf.getUnsignedByte(offset);
        break;
    case 2:
        frameLength = buf.getUnsignedShort(offset);
        break;
    case 3:
        frameLength = buf.getUnsignedMedium(offset);
        break;
    case 4:
        frameLength = buf.getUnsignedInt(offset);
        break;
    case 8:
        frameLength = buf.getLong(offset);
        break;
    default:
        throw new DecoderException(
                "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: 1, 2, 3, 4, or 8)");
    }
    return frameLength;
}
 
Example 3
Source File: HermesLengthFieldBasedFrameDecoder.java    From hermes with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes the specified region of the buffer into an unadjusted frame length. The default implementation is capable of decoding
 * the specified region into an unsigned 8/16/24/32/64 bit integer. Override this method to decode the length field encoded
 * differently. Note that this method must not modify the state of the specified buffer (e.g. {@code readerIndex},
 * {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException
 *            if failed to decode the specified region
 */
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
	buf = buf.order(order);
	long frameLength;
	switch (length) {
	case 1:
		frameLength = buf.getUnsignedByte(offset);
		break;
	case 2:
		frameLength = buf.getUnsignedShort(offset);
		break;
	case 3:
		frameLength = buf.getUnsignedMedium(offset);
		break;
	case 4:
		frameLength = buf.getUnsignedInt(offset);
		break;
	case 8:
		frameLength = buf.getLong(offset);
		break;
	default:
		throw new DecoderException("unsupported lengthFieldLength: " + lengthFieldLength
		      + " (expected: 1, 2, 3, 4, or 8)");
	}
	return frameLength;
}
 
Example 4
Source File: UaTcpClientAcknowledgeHandler.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH &&
            buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
            case Acknowledge:
                onAcknowledge(ctx, buffer.readSlice(messageLength));
                break;

            case Error:
                onError(ctx, buffer.readSlice(messageLength));
                break;

            default:
                out.add(buffer.readSlice(messageLength).retain());
        }
    }
}
 
Example 5
Source File: UaTcpServerHelloHandler.java    From opc-ua-stack with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH &&
            buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
            case Hello:
                onHello(ctx, buffer.readSlice(messageLength));
                break;

            default:
                throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                        "unexpected MessageType: " + messageType);
        }
    }
}
 
Example 6
Source File: OrderedByteBufferTest.java    From netty.book.kor with MIT License 5 votes vote down vote up
@Test
public void pooledHeapBufferTest() {
    ByteBuf buf = Unpooled.buffer(11);
    assertEquals(ByteOrder.BIG_ENDIAN, buf.order());

    buf.markReaderIndex();
    buf.writeShort(1);
    assertEquals(1, buf.readShort());

    buf.resetReaderIndex();

    ByteBuf lettleEndianBuf = buf.order(ByteOrder.LITTLE_ENDIAN);
    assertEquals(256, lettleEndianBuf.readShort());
}
 
Example 7
Source File: Packet.java    From Ogar2-Server with GNU General Public License v3.0 5 votes vote down vote up
public static String readUTF16(ByteBuf in) {
    in = in.order(ByteOrder.BIG_ENDIAN);
    ByteBuf buffer = in.alloc().buffer();
    char chr;
    while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
        buffer.writeChar(chr);
    }

    return buffer.toString(Charsets.UTF_16LE);
}
 
Example 8
Source File: StringLengthFieldBasedFrameDecoder.java    From jreactive-8583 with Apache License 2.0 5 votes vote down vote up
@Override
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    byte[] lengthBytes = new byte[length];
    buf.getBytes(offset, lengthBytes);
    String s = new String(lengthBytes, CharsetUtil.US_ASCII);
    return Long.parseLong(s);
}
 
Example 9
Source File: MysqlHeaderFactory.java    From Mycat-Balance with Apache License 2.0 5 votes vote down vote up
public ByteBuf encode()
{
	ByteBuf _byteBuf = Unpooled.buffer(bodyLength + HEADER_LEN);
	ByteBuf byteBuf = _byteBuf.order(ByteOrder.LITTLE_ENDIAN);

	boolean xx = _byteBuf == byteBuf;

	byteBuf.setInt(0, bodyLength);
	byteBuf.setByte(3, serialNum);
	byteBuf.writerIndex(byteBuf.capacity());
	byteBuf.readerIndex(4);
	return byteBuf;
}
 
Example 10
Source File: WebSocket08FrameDecoder.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void unmask(ByteBuf frame) {
    int i = frame.readerIndex();
    int end = frame.writerIndex();

    ByteOrder order = frame.order();

    // Remark: & 0xFF is necessary because Java will do signed expansion from
    // byte to int which we don't want.
    int intMask = ((maskingKey[0] & 0xFF) << 24)
                | ((maskingKey[1] & 0xFF) << 16)
                | ((maskingKey[2] & 0xFF) << 8)
                | (maskingKey[3] & 0xFF);

    // If the byte order of our buffers it little endian we have to bring our mask
    // into the same format, because getInt() and writeInt() will use a reversed byte order
    if (order == ByteOrder.LITTLE_ENDIAN) {
        intMask = Integer.reverseBytes(intMask);
    }

    for (; i + 3 < end; i += 4) {
        int unmasked = frame.getInt(i) ^ intMask;
        frame.setInt(i, unmasked);
    }
    for (; i < end; i++) {
        frame.setByte(i, frame.getByte(i) ^ maskingKey[i % 4]);
    }
}
 
Example 11
Source File: Packet.java    From Clither-Server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static String readUTF16(ByteBuf in) {
       in = in.order(ByteOrder.BIG_ENDIAN);
       ByteBuf buffer = in.alloc().buffer();
       char chr;
       while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
           buffer.writeChar(chr);
       }

       return buffer.toString(Charsets.UTF_16LE);
   }
 
Example 12
Source File: EnipCodec.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    ByteBuf buffer = in.order(ByteOrder.LITTLE_ENDIAN);

    int startIndex = buffer.readerIndex();

    while (buffer.readableBytes() >= HEADER_SIZE &&
        buffer.readableBytes() >= HEADER_SIZE + getLength(buffer, startIndex)) {

        out.add(EnipPacket.decode(buffer));

        startIndex = buffer.readerIndex();
    }
}
 
Example 13
Source File: APDUEncoder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void handleSFormat ( final Supervisory msg, ByteBuf out )
{
    out = out.order ( ByteOrder.LITTLE_ENDIAN );

    out.ensureWritable ( 6 );
    out.writeByte ( Constants.START_BYTE );
    out.writeByte ( 4 );
    out.writeBytes ( new byte[] { 0x01, 0x00 } );
    out.writeShort ( msg.getReceiveSequenceNumber () << 1 );
}
 
Example 14
Source File: HandshakePacket.java    From Mycat-Balance with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws DecodeException
 */
public static void main(String[] args)
{
	byte[] bs = new byte[] { 82, 0, 0, 0, 10, 49, 48, 46, 48, 46, 49, 45, 77, 97, 114, 105, 97, 68, 66, 0, -98, 1,
			0, 0, 110, 104, 61, 56, 64, 122, 101, 107, 0, -1, -9, 8, 2, 0, 15, -96, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 105, 78, 41, 35, 111, 43, 39, 124, 98, 82, 87, 60, 0, 109, 121, 115, 113, 108, 95, 110, 97, 116,
			105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0 };
	ByteBuf byteBuf = Unpooled.buffer(bs.length);
	byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

	byteBuf.setBytes(0, bs);

	HandshakePacket handshakePacket = new HandshakePacket();
	try
	{
		handshakePacket.decode(byteBuf);
		byteBuf.readerIndex(0);
		
		handshakePacket.decode(byteBuf);
		byteBuf.readerIndex(0);
		
		handshakePacket.decode(byteBuf);
		byteBuf.readerIndex(0);
		
		handshakePacket.decode(byteBuf);
		byteBuf.readerIndex(0);
	} catch (DecodeException e)
	{
		e.printStackTrace();
	}

}
 
Example 15
Source File: UaTcpServerAsymmetricHandler.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    while (buffer.readableBytes() >= HEADER_LENGTH &&
            buffer.readableBytes() >= getMessageLength(buffer)) {

        int messageLength = getMessageLength(buffer);
        MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex()));

        switch (messageType) {
            case OpenSecureChannel:
                onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
                break;

            case CloseSecureChannel:
                logger.debug("Received CloseSecureChannelRequest");
                if (secureChannel != null) {
                    server.closeSecureChannel(secureChannel);
                }
                buffer.skipBytes(messageLength);
                break;

            default:
                throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                        "unexpected MessageType: " + messageType);
        }
    }
}
 
Example 16
Source File: ZclDataUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static void writeBits(ByteBuf output, long value, int bytes) throws IOException {
   long result = value;
   long shift = 8 * (bytes - 1);
   if (output.order() == ByteOrder.LITTLE_ENDIAN) {
      for (int i = 0; i < bytes; ++i) {
         output.writeByte((byte)result);
         result = (result >> 8);
      }
   } else {
      for (int i = 0; i < bytes; ++i) {
         output.writeByte((byte)((result >> shift) & 0xFFL));
         result = result << 8;
      }
   }
}
 
Example 17
Source File: SslUtils.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static short shortBE(ByteBuf buffer, int offset) {
    return buffer.order() == ByteOrder.BIG_ENDIAN ?
            buffer.getShort(offset) : buffer.getShortLE(offset);
}
 
Example 18
Source File: LengthFieldPrependerLittleEndian.java    From mongowp with Apache License 2.0 4 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
  super.encode(ctx, msg, out.order(ByteOrder.LITTLE_ENDIAN));
}
 
Example 19
Source File: SslUtils.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static int unsignedShortBE(ByteBuf buffer, int offset) {
    return buffer.order() == ByteOrder.BIG_ENDIAN ?
            buffer.getUnsignedShort(offset) : buffer.getUnsignedShortLE(offset);
}
 
Example 20
Source File: ResizableMemoryBlock.java    From tajo with Apache License 2.0 4 votes vote down vote up
public ResizableMemoryBlock(ByteBuf buffer, ResizableLimitSpec limitSpec) {
  this.buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
  this.limitSpec = limitSpec;
  this.memoryAddress = this.buffer.hasMemoryAddress() ? this.buffer.memoryAddress() : 0;
}