Example usage for io.netty.buffer ByteBuf isReadable

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

Introduction

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

Prototype

public abstract boolean isReadable();

Source Link

Document

Returns true if and only if (this.writerIndex - this.readerIndex) is greater than 0 .

Usage

From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    Command c = null;// w w w .  j av a  2 s .  co  m
    do {
        in.markReaderIndex();
        c = parse(in);
        if (c == null) {
            in.resetReaderIndex();
            return;
        }
        out.add(c);
    } while (in.isReadable()); // Try to take advantage of pipelining if it is being used
}

From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java

License:Apache License

private Command parse(ByteBuf buffer) throws RedisCommandParserException {
    if (buffer == null)
        throw new NullPointerException();
    if (!buffer.isReadable())
        return null;

    byte firstB = buffer.readByte();
    if (firstB != arrayID)
        throw new RedisCommandParserException("Expected: " + (char) arrayID + " Actual: " + (char) firstB);
    ArrayList<byte[]> commandElems = new ArrayList<byte[]>();

    if (!parseArray(commandElems, buffer))
        return null;

    return new Command(commandElems);
}

From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java

License:Apache License

private boolean parseArray(ArrayList<byte[]> commandElems, ByteBuf buffer) throws RedisCommandParserException {
    byte currentChar;
    int arrayLength = parseCurrentNumber(buffer);
    if (arrayLength == Integer.MIN_VALUE || !parseRN(buffer))
        return false;
    if (arrayLength < 0 || arrayLength > 1000000000)
        throw new RedisCommandParserException("invalid multibulk length");

    for (int i = 0; i < arrayLength; i++) {
        if (!buffer.isReadable())
            return false;
        currentChar = buffer.readByte();
        if (currentChar == bulkStringID) {
            byte[] newBulkString = parseBulkString(buffer);
            if (newBulkString == null)
                return false;
            commandElems.add(newBulkString);
        } else// ww w .  ja  va  2 s  .com
            throw new RedisCommandParserException("expected: \'$\', got \'" + (char) currentChar + "\'");
    }
    return true;
}

From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java

License:Apache License

/**
 * Helper method to parse the number at the beginning of the buffer
 * /*from   www  .j ava  2s .  c  o m*/
 * @param buffer Buffer to read
 * @return The number found at the beginning of the buffer
 */
private int parseCurrentNumber(ByteBuf buffer) {
    int number = 0;
    int readerIndex = buffer.readerIndex();
    byte b = 0;
    while (true) {
        if (!buffer.isReadable())
            return Integer.MIN_VALUE;
        b = buffer.readByte();
        if (Character.isDigit(b)) {
            number = number * 10 + (int) (b - '0');
            readerIndex++;
        } else {
            buffer.readerIndex(readerIndex);
            break;
        }
    }
    return number;
}

From source file:com.github.sparkfy.network.util.TransportFrameDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object data) throws Exception {
    ByteBuf in = (ByteBuf) data;/*from  w ww  . j  a v  a  2  s.c o  m*/
    buffers.add(in);
    totalSize += in.readableBytes();

    while (!buffers.isEmpty()) {
        // First, feed the interceptor, and if it's still, active, try again.
        if (interceptor != null) {
            ByteBuf first = buffers.getFirst();
            int available = first.readableBytes();
            if (feedInterceptor(first)) {
                assert !first.isReadable() : "Interceptor still active but buffer has data.";
            }

            int read = available - first.readableBytes();
            if (read == available) {
                buffers.removeFirst().release();
            }
            totalSize -= read;
        } else {
            // Interceptor is not active, so try to decode one frame.
            ByteBuf frame = decodeNext();
            if (frame == null) {
                break;
            }
            ctx.fireChannelRead(frame);
        }
    }
}

From source file:com.github.sparkfy.network.util.TransportFrameDecoder.java

License:Apache License

private long decodeFrameSize() {
    if (nextFrameSize != UNKNOWN_FRAME_SIZE || totalSize < LENGTH_SIZE) {
        return nextFrameSize;
    }//from  ww  w  . j  av a2  s .c om

    // We know there's enough data. If the first buffer contains all the data, great. Otherwise,
    // hold the bytes for the frame length in a composite buffer until we have enough data to read
    // the frame size. Normally, it should be rare to need more than one buffer to read the frame
    // size.
    ByteBuf first = buffers.getFirst();
    if (first.readableBytes() >= LENGTH_SIZE) {
        nextFrameSize = first.readLong() - LENGTH_SIZE;
        totalSize -= LENGTH_SIZE;
        if (!first.isReadable()) {
            buffers.removeFirst().release();
        }
        return nextFrameSize;
    }

    while (frameLenBuf.readableBytes() < LENGTH_SIZE) {
        ByteBuf next = buffers.getFirst();
        int toRead = Math.min(next.readableBytes(), LENGTH_SIZE - frameLenBuf.readableBytes());
        frameLenBuf.writeBytes(next, toRead);
        if (!next.isReadable()) {
            buffers.removeFirst().release();
        }
    }

    nextFrameSize = frameLenBuf.readLong() - LENGTH_SIZE;
    totalSize -= LENGTH_SIZE;
    frameLenBuf.clear();
    return nextFrameSize;
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;
    try {/*from   www. ja va 2 s  . co m*/
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.groupon.vertx.memcache.stream.MemcacheInputStream.java

License:Apache License

/**
 * This method handles processing the incoming Buffer from the NetSocket.  The Buffer
 * is not guaranteed to contain a whole message so this method tracks the current state
 * of the incoming data and notifies the pending commands when enough data has been sent
 * for a response.//from   ww w  . ja  va 2 s  .c om
 *
 * @param processBuffer - The Buffer containing the current set of bytes.
 */
public void processBuffer(Buffer processBuffer) {
    if (processBuffer == null || processBuffer.length() == 0) {
        return;
    }

    byte first;
    byte second;

    ByteBuf byteBuf = processBuffer.getByteBuf();

    while (byteBuf.isReadable()) {
        first = byteBuf.readByte();
        if (first == '\r') {
            if (byteBuf.isReadable()) {
                second = byteBuf.readByte();
                if (second == '\n') {
                    addCompletedLine();
                }
                previous = second;
            } else {
                previous = first;
            }
        } else if (first == '\n' && previous == '\r') {
            addCompletedLine();
            previous = first;
        } else {
            buffer.write(first);
            previous = first;
        }
    }
}

From source file:com.groupon.vertx.redis.RedisInputStream.java

License:Apache License

/**
 * This method handles processing the incoming Buffer from the NetSocket.  The Buffer
 * is not guaranteed to contain a whole message so this method tracks the current state
 * of the incoming data and notifies the pending commands when enough data has been sent
 * for a response.//w ww  .  j  av  a 2s . co  m
 *
 * @param processBuffer - The Buffer containing the current set of bytes.
 */
public void processBuffer(Buffer processBuffer) {
    if (processBuffer == null || processBuffer.length() == 0) {
        return;
    }

    byte first;
    byte second;

    ByteBuf byteBuf = processBuffer.getByteBuf();

    while (byteBuf.isReadable()) {
        first = byteBuf.readByte();
        if (first == '\r' && byteBuf.isReadable()) {
            second = byteBuf.readByte();
            if (second == '\n') {
                byte[] line = new byte[bufferPosition];
                System.arraycopy(buffer, 0, line, 0, line.length);
                addCompletedLine(line);
            } else {
                buffer[bufferPosition++] = first;
                buffer[bufferPosition++] = second;
            }
        } else if (first == '\n' && buffer[bufferPosition - 1] == '\r') {
            byte[] line = new byte[bufferPosition - 1];
            System.arraycopy(buffer, 0, line, 0, line.length);
            addCompletedLine(line);
        } else {
            buffer[bufferPosition++] = first;
        }
    }
}

From source file:com.intuit.karate.netty.FeatureServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
    long startTime = System.currentTimeMillis();
    backend.getContext().logger.debug("handling method: {}, uri: {}", msg.method(), msg.uri());
    FullHttpResponse nettyResponse;/*from ww  w. j  a v a2 s .c  o  m*/
    if (msg.uri().startsWith(STOP_URI)) {
        backend.getContext().logger.info("stop uri invoked, shutting down");
        ByteBuf responseBuf = Unpooled.copiedBuffer("stopped", CharsetUtil.UTF_8);
        nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBuf);
        stopFunction.run();
    } else {
        StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri());
        HttpRequest request = new HttpRequest();
        if (url.left == null) {
            String requestScheme = ssl ? "https" : "http";
            String host = msg.headers().get(HttpUtils.HEADER_HOST);
            request.setUrlBase(requestScheme + "://" + host);
        } else {
            request.setUrlBase(url.left);
        }
        request.setUri(url.right);
        request.setMethod(msg.method().name());
        msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue()));
        QueryStringDecoder decoder = new QueryStringDecoder(url.right);
        decoder.parameters().forEach((k, v) -> request.putParam(k, v));
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            byte[] bytes = new byte[content.readableBytes()];
            content.readBytes(bytes);
            request.setBody(bytes);
        }
        HttpResponse response = backend.buildResponse(request, startTime);
        HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(response.getStatus());
        byte[] responseBody = response.getBody();
        if (responseBody != null) {
            ByteBuf responseBuf = Unpooled.copiedBuffer(responseBody);
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, responseBuf);
        } else {
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus);
        }
        MultiValuedMap karateHeaders = response.getHeaders();
        if (karateHeaders != null) {
            HttpHeaders nettyHeaders = nettyResponse.headers();
            karateHeaders.forEach((k, v) -> nettyHeaders.add(k, v));
        }
    }
    ctx.write(nettyResponse);
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}