Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:com.netflix.iep.http.NetflixJsonObjectDecoder.java

License:Apache License

/**
 * Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
 *///from  w  ww  .  j av  a  2  s  . co m
@SuppressWarnings("UnusedParameters")
protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
    if (length == 0)
        return null;
    ByteBuf buf = buffer.slice(index, length).retain();

    if (LOGGER.isTraceEnabled()) {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), bytes, 0, buf.readableBytes());
        LOGGER.trace("extracted [" + buf.readerIndex() + ":" + buf.readableBytes() + "]:" + new String(bytes));
    }

    return buf;
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception {
    ByteBuf clientPrefaceString = Http2CodecUtil.connectionPrefaceBuf();
    int prefaceRemaining = clientPrefaceString.readableBytes();
    int bytesRead = min(in.readableBytes(), prefaceRemaining);

    // If the input so far doesn't match the preface, break the connection.
    if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(), clientPrefaceString,
            clientPrefaceString.readerIndex(), bytesRead)) {
        String receivedBytes = hexDump(in, in.readerIndex(),
                min(in.readableBytes(), clientPrefaceString.readableBytes()));
        throw connectionError(PROTOCOL_ERROR,
                "HTTP/2 client preface string missing or corrupt. " + "Hex dump for received bytes: %s",
                receivedBytes);/* ww  w  .  j av a2s  .  c o  m*/
    }
    in.skipBytes(bytesRead);
    clientPrefaceString.skipBytes(bytesRead);

    if (!clientPrefaceString.isReadable()) {
        // Entire preface has been read.
        clientPrefaceString.release();
        return true;
    }
    return false;
}

From source file:com.netty.test.LengthFieldBasedExFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created./* w  w w.ja v a2s. co m*/
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(false);
        return null;
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getFrameLength(in, actualLengthFieldOffset);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - in.readableBytes();
        in.skipBytes(in.readableBytes());
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.ning.http.client.providers.netty_4.ResponseBodyPart.java

License:Apache License

@Override
public int writeTo(OutputStream outputStream) throws IOException {
    ByteBuf b = getChannelBuffer();
    int available = b.readableBytes();
    if (available > 0) {
        b.getBytes(b.readerIndex(), outputStream, available);
    }// w  ww . j  a v  a2  s  . c om
    return available;
}

From source file:com.noctarius.tengi.buffer.ByteBufMemoryBuffer.java

License:Open Source License

@Override
public int readBuffer(MemoryBuffer memoryBuffer) {
    if (memoryBuffer instanceof ByteBufMemoryBuffer) {
        ByteBuf buffer = ((ByteBufMemoryBuffer) memoryBuffer).byteBuffer;
        int pos = buffer.readerIndex();
        byteBuffer.readBytes(buffer);// ww w.j av  a  2  s  . com
        readerIndex += (buffer.readerIndex() - pos);
        return buffer.readerIndex() - pos;
    }

    int writableBytes = memoryBuffer.writableBytes();
    byte[] data = new byte[writableBytes];
    byteBuffer.readBytes(data);
    memoryBuffer.writeBytes(data);
    readerIndex += writableBytes;
    return writableBytes;
}

From source file:com.noctarius.tengi.buffer.ByteBufMemoryBuffer.java

License:Open Source License

@Override
public int readBuffer(MemoryBuffer memoryBuffer, int offset, int length) {
    if (memoryBuffer instanceof ByteBufMemoryBuffer) {
        ByteBuf buffer = ((ByteBufMemoryBuffer) memoryBuffer).byteBuffer;
        int pos = buffer.readerIndex();
        byteBuffer.readBytes(buffer);//from   w w w.j  a  v a2s .co m
        readerIndex += (buffer.readerIndex() - pos);
        return buffer.readerIndex() - pos;
    }

    int writableBytes = memoryBuffer.writableBytes();
    byte[] data = new byte[writableBytes];
    byteBuffer.readBytes(data);
    memoryBuffer.writeBytes(data);
    readerIndex += writableBytes;
    return writableBytes;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.ConnectDecoder.java

License:Open Source License

@Override
public AbstractMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();/*from w  w  w  . j a  va2 s.c  o  m*/
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return null;
    }
    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 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) 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) 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.setProcotolVersion(in.readByte());
    if (message.getProcotolVersion() == 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");
        }
    }

    //PKMPConnection flag
    byte connFlags = in.readByte();
    if (message.getProcotolVersion() == 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.getProcotolVersion() == VERSION_3_1)
            || (remainingLength == 10 && message.getProcotolVersion() == 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) {
        String willMessage = Utils.decodeString(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) {
        String password = Utils.decodeString(in);
        if (password == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setPassword(password);
    }
    return message;
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.PublishDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    LOG.info("decode invoked with buffer {}", in);
    in.resetReaderIndex();/*from   w  w w.java2 s  .c om*/
    int startPos = in.readerIndex();

    //Common decoding part
    PublishMessage message = new PublishMessage();
    if (!decodeCommonHeader(message, in)) {
        LOG.info("decode ask for more data after {}", in);
        in.resetReaderIndex();
        return;
    }

    if (Utils.isMQTT3_1_1(ctx)) {
        if (message.getQos() == AbstractMessage.QOSType.MOST_ONE && message.isDupFlag()) {
            //bad protocol, if QoS=0 => DUP = 0
            throw new CorruptedFrameException("Received a PUBLISH with QoS=0 & DUP = 1, MQTT 3.1.1 violation");
        }

        if (message.getQos() == AbstractMessage.QOSType.RESERVED) {
            throw new CorruptedFrameException(
                    "Received a PUBLISH with QoS flags setted 10 b11, MQTT 3.1.1 violation");
        }
    }

    int remainingLength = message.getRemainingLength();

    //Topic name
    String topic = Utils.decodeString(in);
    if (topic == null) {
        in.resetReaderIndex();
        return;
    }
    if (topic.contains("+") || topic.contains("#")) {
        throw new CorruptedFrameException(
                "Received a PUBLISH with topic containting wild card chars, topic: " + topic);
    }

    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;
    }
    //        byte[] b = new byte[payloadSize];
    ByteBuf bb = Unpooled.buffer(payloadSize);
    in.readBytes(bb);
    message.setPayload(bb.nioBuffer());

    out.add(message);
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.SubscribeDecoder.java

License:Open Source License

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

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

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

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

    out.add(message);
}

From source file:com.pubkit.platform.messaging.protocol.mqtt.proto.parser.UnsubscribeDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();// w  ww . j  av a2 s.c o  m
    UnsubscribeMessage message = new UnsubscribeMessage();
    if (!decodeCommonHeader(message, 0x02, in)) {
        in.resetReaderIndex();
        return;
    }

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

    int start = in.readerIndex();
    //read  messageIDs
    message.setMessageID(in.readUnsignedShort());
    int readed = in.readerIndex() - start;
    while (readed < message.getRemainingLength()) {
        message.addTopicFilter(Utils.decodeString(in));
        readed = in.readerIndex() - start;
    }
    if (message.topicFilters().isEmpty()) {
        throw new CorruptedFrameException("unsubscribe MUST have got at least 1 topic");
    }
    out.add(message);
}