Example usage for io.netty.buffer ByteBuf markReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf markReaderIndex();

Source Link

Document

Marks the current readerIndex in this buffer.

Usage

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;/* w  ww  . j a v  a  2 s .c o  m*/
    }

    // 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;
    }//  w  w w. j  a va 2s.  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();
    final byte[] contentBytes = IOUtils.toByteArray(new ByteBufInputStream(content));
    content.resetReaderIndex();/*w  ww. j  ava  2s.c om*/

    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();
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();//from  www.  j  a va  2  s. c  om
        } 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();
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();//from  w  ww.  j a  va2  s  . c  o m
            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();
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();/*w ww . jav  a  2s  .c  o  m*/
        } 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.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();
    int preIndex = in.readerIndex();
    int length = readRawVarint32(in);
    if (preIndex == in.readerIndex()) {
        return;/*  w w  w  .  j ava2s  .  c om*/
    }
    if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
    }

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

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

License:Apache License

/**
 * Reads variable length 32bit int from buffer
 *
 * @return decoded int if buffers readerIndex has been forwarded else nonsense value
 *///  w ww .jav  a  2 s  . c  o m
private static int readRawVarint32(ByteBuf buffer) {
    if (!buffer.isReadable()) {
        return 0;
    }
    buffer.markReaderIndex();
    byte tmp = buffer.readByte();
    if (tmp >= 0) {
        return tmp;
    } else {
        int result = tmp & 127;
        if (!buffer.isReadable()) {
            buffer.resetReaderIndex();
            return 0;
        }
        if ((tmp = buffer.readByte()) >= 0) {
            result |= tmp << 7;
        } else {
            result |= (tmp & 127) << 7;
            if (!buffer.isReadable()) {
                buffer.resetReaderIndex();
                return 0;
            }
            if ((tmp = buffer.readByte()) >= 0) {
                result |= tmp << 14;
            } else {
                result |= (tmp & 127) << 14;
                if (!buffer.isReadable()) {
                    buffer.resetReaderIndex();
                    return 0;
                }
                if ((tmp = buffer.readByte()) >= 0) {
                    result |= tmp << 21;
                } else {
                    result |= (tmp & 127) << 21;
                    if (!buffer.isReadable()) {
                        buffer.resetReaderIndex();
                        return 0;
                    }
                    result |= (tmp = buffer.readByte()) << 28;
                    if (tmp < 0) {
                        throw new CorruptedFrameException("malformed varint.");
                    }
                }
            }
        }
        return result;
    }
}

From source file:com.cloudera.livy.client.local.rpc.KryoMessageCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 4) {
        return;/* www . j a  v  a 2 s. co  m*/
    }

    in.markReaderIndex();
    int msgSize = in.readInt();
    checkSize(msgSize);

    if (in.readableBytes() < msgSize) {
        // Incomplete message in buffer.
        in.resetReaderIndex();
        return;
    }

    try {
        ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize));
        Object msg = serializer.deserialize(nioBuffer);
        LOG.debug("Decoded message of type {} ({} bytes)", msg != null ? msg.getClass().getName() : msg,
                msgSize);
        out.add(msg);
    } finally {
        in.skipBytes(msgSize);
    }
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuffer, List<Object> packets) throws Exception {
    byteBuffer.markReaderIndex();
    DECODE_BUFFER.invoke(vanillaDecoder, ctx, byteBuffer, packets);

    try {//from  www  .j av  a2  s. co  m
        // Reset queue
        finishQueue.clear();

        for (ListIterator<Object> it = packets.listIterator(); it.hasNext();) {
            Object input = it.next();
            Class<?> packetClass = input.getClass();
            NetworkMarker marker = null;

            // Special case!
            handleLogin(packetClass, input);

            if (channelListener.includeBuffer(packetClass)) {
                byteBuffer.resetReaderIndex();
                marker = new NettyNetworkMarker(ConnectionSide.CLIENT_SIDE, getBytes(byteBuffer));
            }

            PacketEvent output = channelListener.onPacketReceiving(this, input, marker);

            // Handle packet changes
            if (output != null) {
                if (output.isCancelled()) {
                    it.remove();
                    continue;
                } else if (output.getPacket().getHandle() != input) {
                    it.set(output.getPacket().getHandle());
                }

                finishQueue.addLast(output);
            }
        }
    } catch (Exception e) {
        channelListener.getReporter().reportDetailed(this, Report
                .newBuilder(REPORT_CANNOT_INTERCEPT_CLIENT_PACKET).callerParam(byteBuffer).error(e).build());
    }
}