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.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
 *///from  w  w w  . j  av a2 s.co  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;/*  ww  w. ja v  a  2  s  .  c  o 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.codnos.dbgp.internal.handlers.DBGpResponseDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> objects) throws Exception {
    final int length = in.readableBytes();
    LOGGER.fine("got something from engine (" + length + " bytes)");
    int nullPosition = in.forEachByte(ByteProcessor.FIND_NUL);
    int readerIndex = in.readerIndex();
    int numberOfBytes = nullPosition - readerIndex;
    LOGGER.fine("found nullposition on " + nullPosition + " and readerIndex is " + readerIndex
            + " calculated number of bytes " + numberOfBytes);
    if (numberOfBytes <= 0) {
        LOGGER.fine("not enough to read, finishing");
        in.resetReaderIndex();
        return;//from  w w w. j  av  a  2s .c o  m
    }
    if (nullPosition > length) {
        LOGGER.fine("have null position further than length, finishing");
        in.resetReaderIndex();
        return;
    }
    ByteBuf sizeBuf = in.readBytes(numberOfBytes);
    in.readByte();
    String sizeBufAsString = sizeBuf.toString(UTF_8);
    int size = Integer.parseInt(sizeBufAsString);
    int expectedSize = sizeBuf.readableBytes() + NULL_BYTE_SIZE + size + NULL_BYTE_SIZE;
    if (length < expectedSize) {
        LOGGER.fine("don't have the whole message yet (expected " + expectedSize + "), finishing");
        in.resetReaderIndex();
        sizeBuf.release();
        return;
    }
    ByteBuf messageBuf = in.readBytes(size);
    in.readByte();
    objects.add(messageBuf.toString(UTF_8));
    sizeBuf.release();
    messageBuf.release();
}

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();/* w w  w  .j a  v a  2 s  . c  o  m*/
    DECODE_BUFFER.invoke(vanillaDecoder, ctx, byteBuffer, packets);

    try {
        // 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());
    }
}

From source file:com.dempe.chat.common.mqtt.codec.ConnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {
    in.resetReaderIndex();
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();//  w  w w. j a v  a 2 s. com
        return;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

    int protocolNameLen = in.readUnsignedShort();
    byte[] encProtoName;
    String protoName;
    Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION);
    switch (protocolNameLen) {
    case 6:
        //MQTT version 3.1 "MQIsdp"
        //ProtocolName 8 bytes or 6 bytes
        if (in.readableBytes() < 10) {
            in.resetReaderIndex();
            return;
        }

        encProtoName = new byte[6];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQIsdp".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);

        versionAttr.set((int) Utils.VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return;
        }
        encProtoName = new byte[4];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQTT".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);
        versionAttr.set((int) Utils.VERSION_3_1_1);
        break;
    default:
        //protocol broken
        throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen);
    }

    //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1)
    message.setProtocolVersion(in.readByte());
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag()
                || message.getQos() != AbstractMessage.QOSType.MOST_ONE) {
            throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0");
        }

        //check if this is another connect from the same client on the same session
        Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS);
        Boolean alreadyConnected = connectAttr.get();
        if (alreadyConnected == null) {
            //never set
            connectAttr.set(true);
        } else if (alreadyConnected) {
            throw new CorruptedFrameException("Received a second CONNECT on the same network connection");
        }
    }

    //Connection flag
    byte connFlags = in.readByte();
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0
            throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0");
        }
    }

    boolean cleanSession = ((connFlags & 0x02) >> 1) == 1;
    boolean willFlag = ((connFlags & 0x04) >> 2) == 1;
    byte willQos = (byte) ((connFlags & 0x18) >> 3);
    if (willQos > 2) {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos);
    }
    boolean willRetain = ((connFlags & 0x20) >> 5) == 1;
    boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1;
    boolean userFlag = ((connFlags & 0x80) >> 7) == 1;
    //a password is true iff user is true.
    if (!userFlag && passwordFlag) {
        in.resetReaderIndex();
        throw new CorruptedFrameException(
                "Expected password flag to true if the user flag is true but was: " + passwordFlag);
    }
    message.setCleanSession(cleanSession);
    message.setWillFlag(willFlag);
    message.setWillQos(willQos);
    message.setWillRetain(willRetain);
    message.setPasswordFlag(passwordFlag);
    message.setUserFlag(userFlag);

    //Keep Alive timer 2 bytes
    //int keepAlive = Utils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

    if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1)
            || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) {
        out.add(message);
        return;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        byte[] willMessage = Utils.readFixedLengthContent(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillMessage(willMessage);
    }

    //Compatibility check with v3.0, remaining length has precedence over
    //the user and password flags
    int readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode password
    if (passwordFlag) {
        byte[] password = Utils.readFixedLengthContent(in);
        if (password == null) {
            in.resetReaderIndex();
            return;
        }
        message.setPassword(password);
    }

    out.add(message);
}

From source file:com.dempe.chat.common.mqtt.codec.DisconnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();
    DisconnectMessage message = new DisconnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();/*from   www .  j a  v  a2s. c  om*/
        return;
    }
    out.add(message);
}

From source file:com.dempe.chat.common.mqtt.codec.MessageIDDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    in.resetReaderIndex();
    //Common decoding part
    MessageIDMessage message = createMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();/*  w w w  .  j  ava 2s  .  com*/
        return;
    }

    //read  messageIDs
    message.setMessageID(in.readUnsignedShort());
    out.add(message);
}

From source file:com.dempe.chat.common.mqtt.codec.MQTTDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();/*from   w  w  w  .  j  av a 2  s.c  o  m*/
    if (!Utils.checkHeaderAvailability(in)) {
        in.resetReaderIndex();
        return;
    }
    in.resetReaderIndex();

    byte messageType = Utils.readMessageType(in);

    DemuxDecoder decoder = m_decoderMap.get(messageType);
    if (decoder == null) {
        throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + messageType);
    }
    decoder.decode(ctx, in, out);
}

From source file:com.dempe.chat.common.mqtt.codec.PingReqDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();
    PingReqMessage message = new PingReqMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();//from ww w .  j a v a  2  s  .  co m
        return;
    }
    out.add(message);
}

From source file:com.dempe.chat.common.mqtt.codec.PingRespDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();
    PingRespMessage message = new PingRespMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();//from   w w w .j a v  a  2s.  c  o m
        return;
    }
    out.add(message);
}