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

The following examples show how to use io.netty.buffer.ByteBuf#discardReadBytes() . 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: RntbdContextRequestDecoder.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Decode an RntbdContextRequest from an {@link ByteBuf} stream
 * <p>
 * This method will be called till either an input {@link ByteBuf} has nothing to readTree on return from this method or
 * till nothing is readTree from the input {@link ByteBuf}.
 *
 * @param context the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param in      the {@link ByteBuf} from which to readTree data
 * @param out     the {@link List} to which decoded messages should be added
 * @throws IllegalStateException thrown if an error occurs
 */
@Override
protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) throws IllegalStateException {

    final RntbdContextRequest request;
    in.markReaderIndex();

    try {
        request = RntbdContextRequest.decode(in);
    } catch (final IllegalStateException error) {
        in.resetReaderIndex();
        throw error;
    }

    in.discardReadBytes();
    out.add(request);
}
 
Example 2
Source File: RntbdRequestDecoder.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Decode the input {@link ByteBuf} to an {@link RntbdRequest} instance.
 * <p>
 * This method will be called till either the input {@link ByteBuf} has nothing to readTree after return from this
 * method or till nothing was readTree from the input {@link ByteBuf}.
 *
 * @param context the {@link ChannelHandlerContext} to which this {@link ByteToMessageDecoder} belongs.
 * @param in the {@link ByteBuf} from which to read data.
 * @param out the {@link List} to which decoded messages should be added.
 *
 * @throws IllegalStateException thrown if an error occurs
 */
@Override
protected void decode(
    final ChannelHandlerContext context,
    final ByteBuf in,
    final List<Object> out) throws IllegalStateException {

    final RntbdRequest request;
    in.markReaderIndex();

    try {
        request = RntbdRequest.decode(in);
    } catch (final IllegalStateException error) {
        in.resetReaderIndex();
        throw error;
    }

    in.discardReadBytes();
    out.add(request);
}
 
Example 3
Source File: JsonResponseCallbackHandler.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    byte[] buffer = new byte[msg.readableBytes()];
    msg.readBytes(buffer);
    msg.discardReadBytes();

    T object = null;

    try {
        object = objectMapper.readValue(buffer, typeReference);
    } catch (Exception e) {
        callback.onError(e);
        throw new RuntimeException(e);
    }

    callback.onNext(object);
}
 
Example 4
Source File: StringDecoder.java    From YuRPC with Apache License 2.0 5 votes vote down vote up
/**
 * 解码
 *
 * @param chc
 * @param byteBuf
 * @param list
 * @throws Exception
 */
@Override
protected void decode(ChannelHandlerContext chc, ByteBuf byteBuf, List<Object> list) throws Exception {
    try {
        do {
            int readerIndex = byteBuf.readerIndex();
            int readableBytesSize = byteBuf.readableBytes();
            if (readableBytesSize < 4) {
                byteBuf.readerIndex(readerIndex);
                break;
            }
            int size = byteBuf.readInt();
            if (readableBytesSize - 4 < size) {
                byteBuf.readerIndex(readerIndex);
                break;
            }
            byteBuf.readerIndex(readerIndex);
            ByteBuffer byteBuffer = ByteBuffer.allocate(4 + size);
            byteBuf.readBytes(byteBuffer);
            byte[] data = byteBuffer.array();
            byte[] body = Arrays.copyOfRange(data, 4, data.length);
            list.add(new String(body, "UTF-8"));
        } while (byteBuf.isReadable());
    } finally {
        if (byteBuf.isReadable()) {
            byteBuf.discardReadBytes();
        }
    }
}
 
Example 5
Source File: RntbdResponseDecoder.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
/**
 * Deserialize from an input {@link ByteBuf} to an {@link RntbdResponse} instance.
 * <p>
 * This method is called till it reads no bytes from the {@link ByteBuf} or there is no more data to be read.
 *
 * @param context the {@link ChannelHandlerContext} to which this {@link RntbdResponseDecoder} belongs.
 * @param in the {@link ByteBuf} to which data to be decoded is read.
 * @param out the {@link List} to which decoded messages are added.
 */
@Override
protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) {

    if (RntbdFramer.canDecodeHead(in)) {

        final RntbdResponse response = RntbdResponse.decode(in);

        if (response != null) {
            logger.debug("{} DECODE COMPLETE: {}", context.channel(), response);
            in.discardReadBytes();
            out.add(response.retain());
        }
    }
}
 
Example 6
Source File: Framer.java    From besu with Apache License 2.0 4 votes vote down vote up
/**
 * Deframes a full message from the byte buffer, if possible.
 *
 * <p>If the byte buffer contains insufficient bytes to extract a full message, this method
 * returns <code>null</code>.
 *
 * <p>If the buffer contains at least a header, it offloads it and processes it, setting an
 * internal expectation to subsequently receive as many bytes for the frame as the header
 * specified. In this case, this method also returns <code>null</code> to inform the caller that
 * it requires more bytes before it can produce an output.
 *
 * <p>This method can be called repetitively whenever new bytes appear in the buffer. It is worthy
 * to note that the byte buffer is not consumed unless the next expected amount of bytes appears.
 *
 * <p>If there is more than one message in the byte buffer, only the first one is returned,
 * consuming it from the byte buffer. The caller should call this method again with the same byte
 * buffer to continue extracting more messages, if possible.
 *
 * <p>When this method throws an exception, it is recommended that the caller scraps away the RLPx
 * connection, as the digests and stream ciphers could have become corrupted.
 *
 * @param buf The buffer containing no messages, partial messages or multiple messages.
 * @return The first fully extracted message from this buffer, or <code>null</code> if no message
 *     could be extracted yet.
 * @throws FramingException Thrown when a decryption or internal error occurs.
 */
public synchronized MessageData deframe(final ByteBuf buf) throws FramingException {
  if (buf == null || !buf.isReadable()) {
    return null;
  }

  if (!headerProcessed) {
    // We don't have enough bytes to read the header.
    if (buf.readableBytes() < LENGTH_FULL_HEADER) {
      return null;
    }
    frameSize = processHeader(buf.readSlice(LENGTH_FULL_HEADER));
    headerProcessed = true;
    buf.discardReadBytes();
  }

  final int size = frameSize + padding16(frameSize) + LENGTH_MAC;
  if (buf.readableBytes() < size) {
    return null;
  }

  final MessageData msg = processFrame(buf.readSlice(size), frameSize);
  buf.discardReadBytes();
  headerProcessed = false;
  return msg;
}
 
Example 7
Source File: RequestNettyPBDecoder.java    From PeonyFramwork with Apache License 2.0 4 votes vote down vote up
@Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception {
        ByteBuf b = null;
        try {
//        log.info(in.capacity()+";"+in.getClass());
            int readAble = in.readableBytes();
//        log.info("readAble:"+readAble);
            if (readAble < size) {
                return;
            }
            int opcode = 0, id = 0;
            if (!isReadHead) {
                size = in.readInt();
                opcode = in.readInt();
                id = in.readInt();

                isReadHead = true;
                if (size > readAble - headSize) {
                    return;
                }
            }
            b = in.readBytes(size); // 这里有data
            byte[] bbb = new byte[size];
            b.getBytes(0, bbb);
            // add之后好像in就被重置了
            in.discardReadBytes();
            NettyPBPacket nettyPBPacket = new NettyPBPacket();
            nettyPBPacket.setData(bbb);
            nettyPBPacket.setOpcode(opcode);
            nettyPBPacket.setId(id);
            list.add(nettyPBPacket);
            // 清理临时变量
            size = headSize;
            isReadHead = false;
        }catch (Throwable e){
            throw e;
        }finally {
            if(b != null){
                b.release();
            }
        }
    }
 
Example 8
Source File: HttpResponseHandler.java    From docker-java with Apache License 2.0 4 votes vote down vote up
private String getBodyAsMessage(ByteBuf body) {
    String result = body.readBytes(body.readableBytes()).toString(Charset.forName("UTF-8"));
    body.discardReadBytes();
    body.release();
    return result;
}
 
Example 9
Source File: NettyFrameDecoder.java    From TransFIX with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * TODO: loop for more messages in the ByteBuf
 */
void doDecode(ByteBuf in, List<Object> out) {
    if (m_msgLength == -1) {
        if (in.readableBytes() >= NettyFrameHelper.MSG_MIN_BYTES) {
            //int rindex = in.readerIndex();

            int bsi = in.indexOf(0, 12, NettyFrameHelper.BYTE_SOH);
            int bli = in.indexOf(12, 20, NettyFrameHelper.BYTE_SOH);

            // check the existence of:
            // - BeginString 8=
            // - BodyLength  9=
            if (in.getByte(0) == NettyFrameHelper.BYTE_BEGIN_STRING &&
                    in.getByte(1) == NettyFrameHelper.BYTE_EQUALS &&
                    in.getByte(bsi + 1) == NettyFrameHelper.BYTE_BODY_LENGTH &&
                    in.getByte(bsi + 2) == NettyFrameHelper.BYTE_EQUALS) {
                int bodyLength = 0;
                for (int i = bsi + 3; i < bli; i++) {
                    bodyLength *= 10;
                    bodyLength += ((int) in.getByte(i) - (int) '0');
                }

                m_msgLength = 1 + bodyLength + bli + NettyFrameHelper.MSG_CSUM_LEN;

            } else {
                throw new Error("Unexpected state (header)");
            }
        }
    }

    if (m_msgLength != -1 && in.readableBytes() >= m_msgLength) {
        if (in.readableBytes() >= m_msgLength) {
            byte[] rv = new byte[m_msgLength];
            in.readBytes(rv);
            in.discardReadBytes();

            //TODO: validate checksum
            out.add(rv);

            m_msgLength = -1;

        } else {
            throw new Error("Unexpected state (body)");
        }
    }
}