Example usage for io.netty.buffer ByteBuf resetReaderIndex

List of usage examples for io.netty.buffer ByteBuf resetReaderIndex

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf resetReaderIndex.

Prototype

public abstract ByteBuf resetReaderIndex();

Source Link

Document

Repositions the current readerIndex to the marked readerIndex in this buffer.

Usage

From source file:com.antsdb.saltedfish.server.mysql.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // do we have length field in buffer ?

    if (!in.isReadable(4)) {
        return;//  w w  w . j a  va  2  s . c  o m
    }

    // do we have entire packet in the buffer?

    in.markReaderIndex();
    int size = BufferUtils.readLongInt(in);
    int sequence = in.readByte() & 0xff;
    if (size == 0) {
        out.add(new ShutdownPacket());
        return;
    }
    if (!in.isReadable(size)) {
        in.resetReaderIndex();
        return;
    }

    // is very large packet?

    this.handler.packetSequence = sequence;
    if (size == MAX_PACKET_SIZE) {
        if (this.largePacket == null) {
            this.largePacket = ctx.alloc().directBuffer();
        }
        this.largePacket.writeBytes(in, MAX_PACKET_SIZE);
        return;
    }
    if (this.largePacket != null) {
        this.largePacket.writeBytes(in, size);
    }

    // parse packet

    if (this.largePacket == null) {
        int pos = in.readerIndex();
        try {
            RecievePacket packet = readPacket(in, size);
            out.add(packet);
        } finally {
            in.readerIndex(pos + size);
        }
    } else {
        RecievePacket packet = readPacket(this.largePacket, size);
        out.add(packet);
        this.largePacket.release();
        this.largePacket = null;
    }
}

From source file:com.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // do we have length field in buffer ?
    if (!in.isReadable(4)) {
        return;//from  w w w .  j  a  v a 2 s .  c  om
    }

    // do we have entire packet in the buffer?

    in.markReaderIndex();
    int size = BufferUtils.readLongInt(in) + 1;
    if (size == (0x00ffffff + 1)) {
        return;
    }
    if (!in.isReadable(size)) {
        in.resetReaderIndex();
        return;
    }

    int pos = in.readerIndex();
    try {
        ReplicationPacket packet = readPacket(in, size);
        out.add(packet);
    } finally {
        int currentPos = in.readerIndex();
        in.skipBytes(size - (currentPos - pos));
    }
}

From source file:com.baidu.jprotobuf.pbrpc.transport.handler.RpcDataPackageDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {

    // Make sure if the length field was received.
    if (buf.readableBytes() < RpcHeadMeta.SIZE) {
        // The length field was not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return null;
    }//from  w  w  w. j a va  2  s  .  co  m

    // The length field is in the buffer.

    // Mark the current buffer position before reading the length field
    // because the whole frame might not be in the buffer yet.
    // We will reset the buffer position to the marked position if
    // there's not enough bytes in the buffer.
    buf.markReaderIndex();

    // Read the RPC head
    long rpcMessageDecoderStart = System.nanoTime();
    ByteBuffer buffer = buf.nioBuffer(buf.readerIndex(), RpcHeadMeta.SIZE);

    buffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] bytes = new byte[RpcHeadMeta.SIZE];
    buffer.get(bytes);

    RpcHeadMeta headMeta = new RpcHeadMeta();
    headMeta.read(bytes);

    // get total message size
    int messageSize = headMeta.getMessageSize() + RpcHeadMeta.SIZE;

    // Make sure if there's enough bytes in the buffer.
    if (buf.readableBytes() < messageSize) {
        // The whole bytes were not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.

        // Reset to the marked position to read the length field again
        // next time.
        buf.resetReaderIndex();

        return null;
    }

    // check magic code
    String magicCode = headMeta.getMagicCodeAsString();
    if (!ProtocolConstant.MAGIC_CODE.equals(magicCode)) {
        throw new Exception("Error magic code:" + magicCode);
    }
    // There's enough bytes in the buffer. Read it.
    byte[] totalBytes = new byte[messageSize];
    buf.readBytes(totalBytes, 0, messageSize);

    RpcDataPackage rpcDataPackage = new RpcDataPackage();
    rpcDataPackage.setTimeStamp(System.currentTimeMillis());
    rpcDataPackage.read(totalBytes);

    // check if a chunk package
    if (rpcDataPackage.isChunkPackage()) {

        Long chunkStreamId = rpcDataPackage.getChunkStreamId();

        RpcDataPackage chunkDataPackage = tempTrunkPackages.get(chunkStreamId);
        if (chunkDataPackage == null) {
            chunkDataPackage = rpcDataPackage;
            tempTrunkPackages.put(chunkStreamId, rpcDataPackage);
        } else {
            chunkDataPackage.mergeData(rpcDataPackage.getData());
        }

        if (rpcDataPackage.isFinalPackage()) {
            chunkDataPackage.chunkInfo(chunkStreamId, -1);
            tempTrunkPackages.remove(chunkStreamId);

            return chunkDataPackage;
        }

        return null;
    }

    long rpcMessageDecoderEnd = System.nanoTime();
    LOG.log(Level.FINE,
            "[profiling] nshead decode cost : " + (rpcMessageDecoderEnd - rpcMessageDecoderStart) / 1000);

    return rpcDataPackage;
}

From source file:com.barchart.netty.rest.server.util.SigningUtil.java

License:BSD License

public static byte[] bytesToSign(final HttpServerRequest request) throws Exception {

    final ByteBuf content = request.getContent();
    content.markReaderIndex();//from w ww .j  a  v a  2s . c o  m
    final byte[] contentBytes = IOUtils.toByteArray(new ByteBufInputStream(content));
    content.resetReaderIndex();

    final String md5 = KerberosUtilities.bytesToHex(MessageDigest.getInstance("MD5").digest(contentBytes));

    final StringBuilder sb = new StringBuilder();
    sb.append(request.getMethod().name()).append("\n").append(request.getUri()).append("\n").append(md5)
            .append("\n").append(nullCheck(request.headers().get(HttpHeaders.Names.CONTENT_TYPE))).append("\n")
            .append(nullCheck(request.headers().get(HttpHeaders.Names.DATE))).append("\n");

    return sb.toString().getBytes("UTF-8");

}

From source file:com.basho.riak.client.core.netty.HealthCheckDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> list) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();//from   ww w .  j ava 2s  .  c  o  m
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
        } else {
            byte code = in.readByte();
            byte[] protobuf = new byte[length - 1];
            in.readBytes(protobuf);

            chc.channel().pipeline().remove(this);
            if (code == RiakMessageCodes.MSG_ErrorResp) {
                logger.debug("Received MSG_ErrorResp reply to healthcheck");
                future.setException((riakErrorToException(protobuf)));
            } else {
                logger.debug("Healthcheck op successful; returned code {}", code);
                future.setMessage(new RiakMessage(code, protobuf));
            }
        }
    }
}

From source file:com.basho.riak.client.core.netty.RiakMessageCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();/* www. j  av  a  2 s . c  om*/
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        } else {
            byte code = in.readByte();
            byte[] array = new byte[length - 1];
            in.readBytes(array);
            out.add(new RiakMessage(code, array));
        }

    }
}

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();/*from   w w w .  j  av  a 2  s. com*/
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
        } else {
            byte code = in.readByte();
            byte[] protobuf = new byte[length - 1];
            in.readBytes(protobuf);

            switch (state) {
            case TLS_WAIT:
                switch (code) {
                case RiakMessageCodes.MSG_StartTls:
                    logger.debug("Received MSG_RpbStartTls reply");
                    // change state
                    this.state = State.SSL_WAIT;
                    // insert SSLHandler
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    // get promise
                    Future<Channel> hsFuture = sslHandler.handshakeFuture();
                    // register callback
                    hsFuture.addListener(new SslListener());
                    // Add handler
                    chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to startTls");
                    promise.tryFailure((riakErrorToException(protobuf)));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during StartTLS; " + code));
                }
                break;
            case AUTH_WAIT:
                chc.channel().pipeline().remove(this);
                switch (code) {
                case RiakMessageCodes.MSG_AuthResp:
                    logger.debug("Received MSG_RpbAuthResp reply");
                    promise.trySuccess(null);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to auth");
                    promise.tryFailure(riakErrorToException(protobuf));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during Auth; " + code));
                }
                break;
            default:
                // WTF?
                logger.error("Received message while not in TLS_WAIT or AUTH_WAIT");
                promise.tryFailure(
                        new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT"));
            }
        }
    }
}

From source file:com.bosscs.spark.commons.extractor.client.codecs.ActionDecoder.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

    // Wait until the length prefix is available.
    if (in.readableBytes() < 5) {
        return;//w w w.  j  a  v  a  2s.  c  o  m
    }

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

    // Convert the received data into a new BigInteger.
    byte[] decoded = new byte[dataLength];
    in.readBytes(decoded);

    ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
    ObjectInput inObj = null;
    Action action = null;
    try {
        inObj = new ObjectInputStream(bis);
        action = (Action) inObj.readObject();
    } catch (IOException | ClassNotFoundException e) {
        LOG.error(e.getMessage());
    } finally {
        try {
            bis.close();
        } catch (IOException ex) {
            // ignore close exception
        }
        try {
            if (inObj != null) {
                inObj.close();
            }
        } catch (IOException ex) {
            // ignore close exception
        }
    }

    out.add(action);
}

From source file:com.bosscs.spark.commons.extractor.client.codecs.ResponseDecoder.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

    // Wait until the length prefix is available.
    if (in.readableBytes() < 5) {
        return;/* w w  w. ja  v a  2  s.c om*/
    }

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

    // Convert the received data into a new BigInteger.
    byte[] decoded = new byte[dataLength];
    in.readBytes(decoded);

    ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
    ObjectInput inObj = null;
    Response response = null;
    try {
        inObj = new ObjectInputStream(bis);
        response = (Response) inObj.readObject();
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            bis.close();
        } catch (IOException ex) {
            // ignore close exception
        }
        try {
            if (inObj != null) {
                inObj.close();
            }
        } catch (IOException ex) {
            // ignore close exception
        }
    }

    out.add(response);
}

From source file:com.chat.common.netty.handler.decode.ProtobufVarint32FrameDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();/*from  www  .j av  a  2  s  .  c o  m*/
    int preIndex = in.readerIndex();
    int length = readRawVarint32(in);
    if (preIndex == in.readerIndex()) {
        return;
    }
    if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
    }

    if (in.readableBytes() < length) {
        in.resetReaderIndex();
    } else {
        out.add(in.readRetainedSlice(length));
    }
}