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.github.sylvek.wsmqttfwd.decoder.ConnectDecoder.java

License:Open Source License

@Override
public ConnectMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();//www.  ja  v a  2s. c om
        return null;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

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

        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 null;
        }
        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)) {
        return message;
    }

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

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

    //Decode willMessage
    if (willFlag) {
        byte[] willMessage = Utils.readFixedLengthContent(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return null;
        }
        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) {
        return message;
    }

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

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

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

    return message;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.PublishDecoder.java

License:Open Source License

@Override
public PublishMessage decode(AttributeMap ctx, ByteBuf in) throws Exception {
    LOG.debug("decode invoked with buffer {}", in);
    in.resetReaderIndex();
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.debug("decode ask for more data after {}", in);
        in.resetReaderIndex();//from  ww w. j a va  2s .co m
        return null;
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return null;
    }
    //[MQTT-3.3.2-2] The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters.
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containing wild card chars, topic: " + topic);
    }
    //check topic is at least one char [MQTT-4.7.3-1]
    if (topic.length() == 0) {
        throw new CorruptedFrameException("Received a PUBLISH with topic without any character");
    }

    message.setTopicName(topic);

    if (message.getQos() == AbstractMessage.QOSType.LEAST_ONE
            || message.getQos() == AbstractMessage.QOSType.EXACTLY_ONCE) {
        message.setMessageID(in.readUnsignedShort());
    }
    int stopPos = in.readerIndex();

    //read the payload
    int payloadSize = remainingLength - (stopPos - startPos - 2)
            + (Utils.numBytesToEncode(remainingLength) - 1);
    if (in.readableBytes() < payloadSize) {
        in.resetReaderIndex();
        return null;
    }
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    return message;
}

From source file:com.github.sylvek.wsmqttfwd.decoder.SubscribeDecoder.java

License:Open Source License

@Override
public SubscribeMessage decode(AttributeMap ctx, ByteBuf in) throws Exception {
    //Common decoding part
    SubscribeMessage message = new SubscribeMessage();
    in.resetReaderIndex();
    if (!decodeCommonHeader(message, 0x02, in)) {
        in.resetReaderIndex();//from ww  w. j  a v a2 s  . co m
        return null;
    }

    //check qos level
    if (message.getQos() != AbstractMessage.QOSType.LEAST_ONE) {
        throw new CorruptedFrameException(
                "Received SUBSCRIBE message with QoS other than LEAST_ONE, was: " + message.getQos());
    }

    int start = in.readerIndex();
    //read  messageIDs
    message.setMessageID(in.readUnsignedShort());
    int read = in.readerIndex() - start;
    while (read < message.getRemainingLength()) {
        decodeSubscription(in, message);
        read = in.readerIndex() - start;
    }

    if (message.subscriptions().isEmpty()) {
        throw new CorruptedFrameException("subscribe MUST have got at least 1 couple topic/QoS");
    }

    return message;
}

From source file:com.heliosapm.streams.metrichub.HubManager.java

License:Apache License

protected ByteBuf updateJsonRequest(final List<TSMeta> tsMetas, final ByteBuf header) {
    try {//from w ww .  j  a va  2s. c  o  m
        final ByteBuf request = BufferManager.getInstance().buffer(header.readableBytes() + 1024);
        request.writeBytes(header);
        header.resetReaderIndex();
        request.writerIndex(request.writerIndex() - REQUEST_CLOSER.length());
        for (TSMeta ts : tsMetas) {
            request.writeCharSequence(new StringBuilder("\"").append(ts.getTSUID()).append("\","), UTF8);
        }
        request.writerIndex(request.writerIndex() - 1);
        request.writeCharSequence(REQUEST_CLOSER, UTF8);
        return request;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.heliosapm.streams.tracing.writers.MultiWriter.java

License:Apache License

/**
 * {@inheritDoc}//from  ww w  .j ava  2s. c o  m
 * @see com.heliosapm.streams.tracing.AbstractMetricWriter#onMetrics(io.netty.buffer.ByteBuf)
 */
@Override
public void onMetrics(final ByteBuf metrics) {
    for (IMetricWriter imw : subWriters) {
        imw.onMetrics(metrics);
        metrics.resetReaderIndex();
    }
}

From source file:com.heliosapm.utils.buffer.BufferManager.java

License:Apache License

/**
 * Reads a UTF string from the passed ByteBuff
 * @param offset int The offset in the buffer to read from
 * @param in The ByteBuf to read from// w  w w .java2 s. c o  m
 * @return the read string
 */
public final static String readUTF(final int offset, final ByteBuf in) {
    try {
        in.markReaderIndex();
        in.readerIndex(offset);
        return readUTF(in);
    } finally {
        in.resetReaderIndex();
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconPacketDecoder.java

License:Open Source License

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

    final String separator = "=================================================================================================";

    //TODO: Move all code logic below to SourceRconPacketBuilder

    log.debug(separator);//w w w .  j  a va 2s  .  com
    log.debug(" ({}) DECODING INCOMING DATA : Bytes Received = {} {}", index.incrementAndGet(),
            in.readableBytes(), index.get() > 1 ? "[Continuation]" : "");
    log.debug(separator);

    String desc = StringUtils.rightPad("Minimum allowable size?", PAD_SIZE);
    //Verify we have the minimum allowable size
    if (in.readableBytes() < 14) {
        log.debug(" [ ] {} = NO (Actual Readable Bytes: {})", desc, in.readableBytes());
        return;
    }
    log.debug(" [x] {} = YES (Actual Readable Bytes: {})", desc, in.readableBytes());

    //Reset if this happens to be not a valid source rcon packet
    in.markReaderIndex();

    //Read and Verify size
    desc = StringUtils.rightPad("Bytes received at least => than the \"declared\" size?", PAD_SIZE);
    int size = in.readIntLE();
    int readableBytes = in.readableBytes();
    if (readableBytes < size) {
        log.debug(" [ ] {} = NO (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size);
        in.resetReaderIndex();
        return;
    }
    log.debug(" [x] {} = YES (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size);

    //Read and verify request id
    desc = StringUtils.rightPad("Request Id within the valid range?", PAD_SIZE);
    int id = in.readIntLE();
    if (!(id == -1 || id == SourceRconUtil.RCON_TERMINATOR_RID || SourceRconUtil.isValidRequestId(id))) {
        log.debug(" [ ] {} = NO (Actual: {})", desc, id);
        in.resetReaderIndex();
        return;
    }
    log.debug(" [x] {} = YES (Actual: {})", desc, id);

    //Read and verify request type
    desc = StringUtils.rightPad("Valid response type?", PAD_SIZE);
    int type = in.readIntLE();
    if (get(type) == null) {
        log.debug(" [ ] {} = NO (Actual: {})", desc, type);
        in.resetReaderIndex();
        return;
    }
    log.debug(" [x] {} = YES (Actual: {} = {})", desc, type, SourceRconResponseType.get(type));

    //Read and verify body
    desc = StringUtils.rightPad("Contains Body?", PAD_SIZE);
    int bodyLength = in.bytesBefore((byte) 0);
    String body = StringUtils.EMPTY;
    if (bodyLength <= 0)
        log.debug(" [ ] {} = NO", desc);
    else {
        body = in.readCharSequence(bodyLength, StandardCharsets.UTF_8).toString();
        log.debug(" [x] {} = YES (Length: {}, Body: {})", desc, bodyLength,
                StringUtils.replaceAll(StringUtils.truncate(body, 30), "\n", "\\\\n"));
    }

    //Peek at the last two bytes and verify that they are null-bytes
    byte bodyTerminator = in.getByte(in.readerIndex());
    byte packetTerminator = in.getByte(in.readerIndex() + 1);

    desc = StringUtils.rightPad("Contains TWO null-terminating bytes at the end?", PAD_SIZE);

    //Make sure the last two bytes are NULL bytes (request id: 999 is reserved for split packet responses)
    if ((bodyTerminator != 0 || packetTerminator != 0) && (id == SourceRconUtil.RCON_TERMINATOR_RID)) {
        log.debug("Skipping {} bytes", in.readableBytes());
        in.skipBytes(in.readableBytes());
        return;
    } else if (bodyTerminator != 0 || packetTerminator != 0) {
        log.debug(" [ ] {} = NO (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator,
                packetTerminator);
        in.resetReaderIndex();
        return;
    } else {
        log.debug(" [x] {} = YES (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator,
                packetTerminator);
        //All is good, skip the last two bytes
        if (in.readableBytes() >= 2)
            in.skipBytes(2);
    }

    //At this point, we can now construct a packet
    log.debug(" [x] Status: PASS (Size = {}, Id = {}, Type = {}, Remaining Bytes = {}, Body Size = {})", size,
            id, type, in.readableBytes(), bodyLength);
    log.debug(separator);

    //Reset the index
    index.set(0);

    //Construct the response packet and send to the next handlers
    SourceRconResponsePacket responsePacket;

    //Did we receive a terminator packet?
    if (this.terminatingPacketsEnabled && id == SourceRconUtil.RCON_TERMINATOR_RID
            && StringUtils.isBlank(body)) {
        responsePacket = new SourceRconTermResponsePacket();
    } else {
        responsePacket = SourceRconPacketBuilder.getResponsePacket(type);
    }

    if (responsePacket != null) {
        responsePacket.setSize(size);
        responsePacket.setId(id);
        responsePacket.setType(type);
        responsePacket.setBody(body);
        log.debug(
                "Decode Complete. Passing response for request id : '{}' to the next handler. Remaining bytes ({})",
                id, in.readableBytes());
        out.add(responsePacket);
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java

License:Open Source License

@Override
public <T extends SourceServerPacket> T construct(ByteBuf data) {
    //Mark Index/* ww  w . j av a2  s. c om*/
    data.markReaderIndex();

    try {
        //Reset the index
        data.readerIndex(0);

        //Verify size
        if (data.readableBytes() < 5)
            throw new IllegalStateException(
                    "Cannot continue processing buffer with less than or equal to 4 bytes");

        //Read protocol header
        int protocolHeader = data.readIntLE();

        //Check if this is a split packet
        if (protocolHeader == 0xFFFFFFFE)
            throw new IllegalStateException("Cannot construct a response from a partial/split packet.");

        //Verify that we have a valid header
        if (protocolHeader != 0xFFFFFFFF)
            throw new IllegalStateException("Protocol header not supported.");

        //Read packet header
        byte packetHeader = data.readByte();

        //Read payload
        byte[] payload = new byte[data.readableBytes()];
        data.readBytes(payload);

        //Verify if packet header is valid
        SourceServerPacket packet = createResponsePacketFromHeader(packetHeader);

        //If packet is empty, means the supplied packet header is not supported
        if (packet == null)
            return null;

        packet.setProtocolHeader(ByteUtils.byteArrayFromInteger(protocolHeader));
        packet.setHeader(packetHeader);
        packet.setPayload(payload);

        return (T) packet;
    } finally {
        data.resetReaderIndex();
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourceRconPacketBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//w  w w  .  j  av a2 s  .  co  m
public <T extends SourceRconPacket> T construct(ByteBuf data) {
    try {
        if (data.readableBytes() < 14) {
            log.warn("Packet is less than 10 bytes. Unsupported packet.");
            if (log.isDebugEnabled())
                log.debug("Unrecognized Packet: \n{}", ByteBufUtil.prettyHexDump(data));
            return null;
        }

        //Remember the reader index
        data.markReaderIndex();

        //Read from the listen
        data.readerIndex(0);
        int size = data.readIntLE();
        int id = data.readIntLE();
        int type = data.readIntLE();

        String body = data.readCharSequence(data.readableBytes() - 2, StandardCharsets.UTF_8).toString();

        SourceRconResponsePacket packet = getResponsePacket(type);

        if (packet != null) {
            //Ok, we have a valid response packet. Lets keep reading.
            packet.setId(id);
            packet.setSize(size);
            packet.setType(type);
            packet.setBody(body);
            return (T) packet;
        }
    } finally {
        //Reset the index
        data.resetReaderIndex();
    }
    return null;
}

From source file:com.ibasco.agql.protocols.valve.steam.master.MasterServerPacketBuilder.java

License:Open Source License

@Override
public <T extends MasterServerPacket> T construct(ByteBuf data) {
    //Mark Index//  w  w w.j  ava2 s  .  c o  m
    data.markReaderIndex();
    try {
        //Reset the index
        data.readerIndex(0);
        //Verify size
        if (data.readableBytes() <= 6)
            throw new IllegalStateException(
                    "Cannot continue processing buffer with less than or equal to 6 bytes");
        //Read header
        byte[] header = new byte[6];
        data.readBytes(header);
        //Read payload
        byte[] payload = new byte[data.readableBytes()];
        data.readBytes(payload);
        //Verify if packet header is valid
        MasterServerResponsePacket packet = new MasterServerResponsePacket();
        packet.setHeader(header);
        packet.setPayload(payload);
        return (T) packet;
    } finally {
        data.resetReaderIndex();
    }
}