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:io.jsync.http.impl.cgbystrom.FlashPolicyHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buffer = (ByteBuf) msg;
    int index = buffer.readerIndex();
    switch (state) {
    case MAGIC1://w  ww . j  av  a 2 s . c  o m
        if (!buffer.isReadable()) {
            return;
        }
        final int magic1 = buffer.getUnsignedByte(index++);
        state = ParseState.MAGIC2;
        if (magic1 != '<') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
            return;
        }
        // fall through
    case MAGIC2:
        if (!buffer.isReadable()) {
            return;
        }
        final int magic2 = buffer.getUnsignedByte(index);
        if (magic2 != 'p') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
        } else {
            ctx.writeAndFlush(Unpooled.copiedBuffer(XML, CharsetUtil.UTF_8))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:io.lettuce.core.protocol.CommandHandlerBenchmark.java

License:Apache License

private void doBenchmark(List<Command> commandStack, ByteBuf response) throws Exception {

    commandHandler.write(CHANNEL_HANDLER_CONTEXT, commandStack, PROMISE);

    int index = response.readerIndex();
    response.retain();//from  w  w  w.  jav a2  s. c o  m

    commandHandler.channelRead(CHANNEL_HANDLER_CONTEXT, response);

    // cleanup
    response.readerIndex(index);
}

From source file:io.lettuce.core.protocol.RedisStateMachine.java

License:Apache License

/**
 * Attempt to decode a redis response and return a flag indicating whether a complete response was read.
 *
 * @param buffer Buffer containing data from the server.
 * @param command the command itself/*  w  w  w .  j a  v  a 2 s  .  com*/
 * @param output Current command output.
 * @return true if a complete response was read.
 */
public boolean decode(ByteBuf buffer, RedisCommand<?, ?, ?> command, CommandOutput<?, ?, ?> output) {
    int length, end;
    ByteBuffer bytes;

    if (debugEnabled) {
        logger.debug("Decode {}", command);
    }

    if (isEmpty(stack)) {
        add(stack, new State());
    }

    if (output == null) {
        return isEmpty(stack);
    }

    loop:

    while (!isEmpty(stack)) {
        State state = peek(stack);

        if (state.type == null) {
            if (!buffer.isReadable()) {
                break;
            }
            state.type = readReplyType(buffer);
            buffer.markReaderIndex();
        }

        switch (state.type) {
        case SINGLE:
            if ((bytes = readLine(buffer)) == null) {
                break loop;
            }

            if (!QUEUED.equals(bytes)) {
                safeSetSingle(output, bytes, command);
            }
            break;
        case ERROR:
            if ((bytes = readLine(buffer)) == null) {
                break loop;
            }
            safeSetError(output, bytes, command);
            break;
        case INTEGER:
            if ((end = findLineEnd(buffer)) == -1) {
                break loop;
            }
            long integer = readLong(buffer, buffer.readerIndex(), end);
            safeSet(output, integer, command);
            break;
        case BULK:
            if ((end = findLineEnd(buffer)) == -1) {
                break loop;
            }
            length = (int) readLong(buffer, buffer.readerIndex(), end);
            if (length == -1) {
                safeSet(output, null, command);
            } else {
                state.type = BYTES;
                state.count = length + 2;
                buffer.markReaderIndex();
                continue loop;
            }
            break;
        case MULTI:
            if (state.count == -1) {
                if ((end = findLineEnd(buffer)) == -1) {
                    break loop;
                }
                length = (int) readLong(buffer, buffer.readerIndex(), end);
                state.count = length;
                buffer.markReaderIndex();
                safeMulti(output, state.count, command);
            }

            if (state.count <= 0) {
                break;
            }

            state.count--;
            addFirst(stack, new State());

            continue loop;
        case BYTES:
            if ((bytes = readBytes(buffer, state.count)) == null) {
                break loop;
            }
            safeSet(output, bytes, command);
            break;
        default:
            throw new IllegalStateException("State " + state.type + " not supported");
        }

        buffer.markReaderIndex();
        remove(stack);

        output.complete(size(stack));
    }

    if (debugEnabled) {
        logger.debug("Decoded {}, empty stack: {}", command, isEmpty(stack));
    }

    return isEmpty(stack);
}

From source file:io.lettuce.core.protocol.RedisStateMachine.java

License:Apache License

private ByteBuffer readLine(ByteBuf buffer) {

    ByteBuffer bytes = null;/*ww  w  .ja va2s.c  om*/
    int end = findLineEnd(buffer);

    if (end > -1) {
        int start = buffer.readerIndex();
        responseElementBuffer.clear();
        int size = end - start - 1;

        if (responseElementBuffer.capacity() < size) {
            responseElementBuffer.capacity(size);
        }

        buffer.readBytes(responseElementBuffer, size);

        bytes = responseElementBuffer.internalNioBuffer(0, size);

        buffer.readerIndex(end + 1);
        buffer.markReaderIndex();
    }
    return bytes;
}

From source file:io.moquette.parser.netty.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();//from  w w w . ja va  2  s . co m
    if (!decodeCommonHeader(message, 0x02, in)) {
        in.resetReaderIndex();
        return;
    }

    //check qos level
    if (message.getQos() != 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");
    }

    out.add(message);
}

From source file:io.moquette.parser.netty.TestUtils.java

License:Open Source License

/**
 * Verify the presence of the given string starting from the current position
 * inside the buffer./*  w w w . ja v a 2  s  . co m*/
 */
static void verifyString(String str, ByteBuf buff) throws UnsupportedEncodingException {
    ByteBuf tmpBuff = Unpooled.buffer(2);
    byte[] raw = str.getBytes("UTF-8");
    tmpBuff.writeShort(raw.length);
    tmpBuff.writeBytes(raw);
    int buffLen = raw.length + 2;
    verifyByteBuf(tmpBuff, buff.slice(buff.readerIndex(), buffLen));
    buff.skipBytes(buffLen);
}

From source file:io.moquette.spi.impl.Utils.java

License:Open Source License

public static byte[] readBytesAndRewind(ByteBuf payload) {
    byte[] payloadContent = new byte[payload.readableBytes()];
    int mark = payload.readerIndex();
    payload.readBytes(payloadContent);/*  ww  w  .ja  va 2s . co  m*/
    payload.readerIndex(mark);
    return payloadContent;
}

From source file:io.nebo.thrift.DefaultThriftFrameDecoder.java

License:Apache License

protected ByteBuf tryDecodeFramedMessage(ChannelHandlerContext ctx, Channel channel, ByteBuf buffer,
        boolean stripFraming) {
    // Framed messages are prefixed by the size of the frame (which doesn't include the
    // framing itself).

    int messageStartReaderIndex = buffer.readerIndex();
    int messageContentsOffset;

    if (stripFraming) {
        messageContentsOffset = messageStartReaderIndex + MESSAGE_FRAME_SIZE;
    } else {//  ww w  .  ja va 2  s. c o m
        messageContentsOffset = messageStartReaderIndex;
    }

    // The full message is larger by the size of the frame size prefix
    int messageLength = buffer.getInt(messageStartReaderIndex) + MESSAGE_FRAME_SIZE;
    int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset;

    if (messageContentsLength > maxFrameSize) {
        throw new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded");
    }

    if (messageLength == 0) {
        // Zero-sized frame: just ignore it and return nothing
        buffer.readerIndex(messageContentsOffset);
        return null;
    } else if (buffer.readableBytes() < messageLength) {
        // Full message isn't available yet, return nothing for now
        return null;
    } else {
        // Full message is available, return it
        ByteBuf messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength);
        buffer.readerIndex(messageStartReaderIndex + messageLength);
        return messageBuffer;
    }
}

From source file:io.nebo.thrift.DefaultThriftFrameDecoder.java

License:Apache License

protected ByteBuf tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ByteBuf buffer,
        TProtocolFactory inputProtocolFactory) throws TException {
    // Perform a trial decode, skipping through
    // the fields, to see whether we have an entire message available.

    int messageLength = 0;
    int messageStartReaderIndex = buffer.readerIndex();

    try {/*from  w w  w  . j  a va 2  s.  com*/
        TNiftyTransport decodeAttemptTransport = new TNiftyTransport(channel, buffer,
                ThriftTransportType.UNFRAMED);
        int initialReadBytes = decodeAttemptTransport.getReadByteCount();
        TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport);

        // Skip through the message
        inputProtocol.readMessageBegin();
        TProtocolUtil.skip(inputProtocol, TType.STRUCT);
        inputProtocol.readMessageEnd();

        messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes;
    } catch (TTransportException | IndexOutOfBoundsException e) {
        // No complete message was decoded: ran out of bytes
        return null;
    } finally {
        if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) {
            throw new TooLongFrameException("Maximum frame size of " + maxFrameSize + " exceeded");
        }

        buffer.readerIndex(messageStartReaderIndex);
    }

    if (messageLength <= 0) {
        return null;
    }

    // We have a full message in the read buffer, slice it off
    ByteBuf messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength);
    buffer.readerIndex(messageStartReaderIndex + messageLength);
    return messageBuffer;
}

From source file:io.nebo.thrift.TNiftyTransport.java

License:Apache License

public TNiftyTransport(Channel channel, ByteBuf in, ThriftTransportType thriftTransportType) {
    this.channel = channel;
    this.in = in;
    this.out = Unpooled.buffer(DEFAULT_OUTPUT_BUFFER_SIZE);
    this.thriftTransportType = thriftTransportType;
    this.initialReaderIndex = in.readerIndex();

    if (!in.hasArray()) {
        buffer = null;//  www  . j a v  a 2s  .  c om
        bufferPosition = 0;
        initialBufferPosition = bufferEnd = -1;
    } else {
        buffer = in.array();
        initialBufferPosition = bufferPosition = in.arrayOffset() + in.readerIndex();
        bufferEnd = bufferPosition + in.readableBytes();
        // Without this, reading from a !in.hasArray() buffer will advance the readerIndex
        // of the buffer, while reading from a in.hasArray() buffer will not advance the
        // readerIndex, and this has led to subtle bugs. This should help to identify
        // those problems by making things more consistent.
        in.readerIndex(in.readerIndex() + in.readableBytes());
    }
}