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:net.tomp2p.synchronization.SyncUtils.java

License:Apache License

public static List<Checksum> decodeChecksums(ByteBuf buf) {
    final List<Checksum> result = new ArrayList<Checksum>();
    while (buf.isReadable()) {
        //16 bytes as its a MD5
        final byte[] me = new byte[16];
        final int weak = buf.readInt();
        buf.readBytes(me);/* w  w w  . j ava  2s.com*/
        result.add(new Checksum(weak, me));
    }
    return result;
}

From source file:netty.echo.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        sb_debug.append("\n>> HTTP REQUEST -----------\n");
        sb_debug.append(request.getProtocolVersion().toString()).append(" ").append(request.getMethod().name())
                .append(" ").append(request.getUri());
        sb_debug.append("\n");
        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> header : headers) {
                sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n");
            }//from  w  ww . j  a v  a2  s  . c  o m
        }
        sb_debug.append("\n");
        System.out.println(sb_debug);
    } else if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf thisContent = content.content();
        if (thisContent.isReadable()) {
            buffer_body.writeBytes(thisContent);
        }
        if (msg instanceof LastHttpContent) {
            sb_debug.append(buffer_body.toString(CharsetUtil.UTF_8));
            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    sb_debug.append(name).append("=");
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        sb_debug.append(value).append(",");
                    }
                    sb_debug.append("\n\n");
                }
            }
            sb_debug.append("\n<< HTTP REQUEST -----------");
        }
    }
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
            Unpooled.wrappedBuffer(sb_debug.toString().getBytes()));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    ctx.write(response);
}

From source file:netty.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);/*from  w w w . j ava2 s  . com*/
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            writeResponse(trailer, ctx);
        }
    }
}

From source file:netty.mmb.http2.Client.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;//from w w w.j  a v a2s.c  o m
    }

    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();
    }
}

From source file:netty.protocol.discard.example.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    // discard/*  ww  w  .j  a v a  2  s. c o  m*/
    ByteBuf in = (ByteBuf) msg;
    while (in.isReadable()) {
        System.out.print((char) in.readByte());
        System.out.flush();
    }
    System.out.println("");
}

From source file:netty5.http.client.HttpResponseHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;/* w ww .  ja  v  a2 s  . co m*/
    }

    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();
    }
}

From source file:network.example.discard.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    // discard/*from   w w w  .j  a v  a 2s.  c o  m*/
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) { // (1)
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg); // (2)
    }
}

From source file:openbns.commons.net.codec.sts.HttpObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    switch (state()) {
    case SKIP_CONTROL_CHARS: {
        try {//from  w  w  w.  j av a 2s .  c om
            skipControlCharacters(buffer);
            checkpoint(State.READ_INITIAL);
        } finally {
            checkpoint();
        }
    }
    case READ_INITIAL:
        try {
            String[] initialLine = splitInitialLine(readLine(buffer, maxInitialLineLength));
            if (initialLine.length < 3) {
                // Invalid initial line - ignore.
                checkpoint(State.SKIP_CONTROL_CHARS);
                return;
            }

            message = createMessage(initialLine);
            checkpoint(State.READ_HEADER);
        } catch (Exception e) {
            out.add(invalidMessage(e));
            return;
        }
    case READ_HEADER:
        try {
            State nextState = readHeaders(buffer);
            checkpoint(nextState);
            if (nextState == State.READ_CHUNK_SIZE) {
                if (!chunkedSupported) {
                    throw new IllegalArgumentException("Chunked messages not supported");
                }
                // Chunked encoding - generate StsMessage first.  HttpChunks will follow.
                out.add(message);
                return;
            }
            if (nextState == State.SKIP_CONTROL_CHARS) {
                // No content is expected.
                out.add(message);
                out.add(LastStsContent.EMPTY_LAST_CONTENT);
                reset();
                return;
            }
            long contentLength = contentLength();
            if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
                out.add(message);
                out.add(LastStsContent.EMPTY_LAST_CONTENT);
                reset();
                return;
            }

            assert nextState == State.READ_FIXED_LENGTH_CONTENT
                    || nextState == State.READ_VARIABLE_LENGTH_CONTENT;

            out.add(message);

            if (nextState == State.READ_FIXED_LENGTH_CONTENT) {
                // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by chunk.
                chunkSize = contentLength;
            }

            // We return here, this forces decode to be called again where we will decode the content
            return;
        } catch (Exception e) {
            out.add(invalidMessage(e));
            return;
        }
    case READ_VARIABLE_LENGTH_CONTENT: {
        // Keep reading data as a chunk until the end of connection is reached.
        int toRead = Math.min(actualReadableBytes(), maxChunkSize);
        if (toRead > 0) {
            ByteBuf content = readBytes(ctx.alloc(), buffer, toRead);
            if (buffer.isReadable()) {
                out.add(new DefaultStsContent(content));
            } else {
                // End of connection.
                out.add(new DefaultLastStsContent(content, validateHeaders));
                reset();
            }
        } else if (!buffer.isReadable()) {
            // End of connection.
            out.add(LastStsContent.EMPTY_LAST_CONTENT);
            reset();
        }
        return;
    }
    case READ_FIXED_LENGTH_CONTENT: {
        int readLimit = actualReadableBytes();

        // Check if the buffer is readable first as we use the readable byte count
        // to create the HttpChunk. This is needed as otherwise we may end up with
        // create a HttpChunk instance that contains an empty buffer and so is
        // handled like it is the last HttpChunk.
        //
        // See https://github.com/commons/commons/issues/433
        if (readLimit == 0) {
            return;
        }

        int toRead = Math.min(readLimit, maxChunkSize);
        if (toRead > chunkSize) {
            toRead = (int) chunkSize;
        }
        ByteBuf content = readBytes(ctx.alloc(), buffer, toRead);
        chunkSize -= toRead;

        if (chunkSize == 0) {
            // Read all content.
            out.add(new DefaultLastStsContent(content, validateHeaders));
            reset();
        } else {
            out.add(new DefaultStsContent(content));
        }
        return;
    }
    /**
     * everything else after this point takes care of reading chunked content. basically, read chunk size,
     * read chunk, read and ignore the CRLF and repeat until 0
     */
    case READ_CHUNK_SIZE:
        try {
            AppendableCharSequence line = readLine(buffer, maxInitialLineLength);
            int chunkSize = getChunkSize(line.toString());
            this.chunkSize = chunkSize;
            if (chunkSize == 0) {
                checkpoint(State.READ_CHUNK_FOOTER);
                return;
            } else {
                checkpoint(State.READ_CHUNKED_CONTENT);
            }
        } catch (Exception e) {
            out.add(invalidChunk(e));
            return;
        }
    case READ_CHUNKED_CONTENT: {
        assert chunkSize <= Integer.MAX_VALUE;
        int toRead = Math.min((int) chunkSize, maxChunkSize);

        StsContent chunk = new DefaultStsContent(readBytes(ctx.alloc(), buffer, toRead));
        chunkSize -= toRead;

        out.add(chunk);

        if (chunkSize == 0) {
            // Read all content.
            checkpoint(State.READ_CHUNK_DELIMITER);
        } else {
            return;
        }
    }
    case READ_CHUNK_DELIMITER: {
        for (;;) {
            byte next = buffer.readByte();
            if (next == StsConstants.CR) {
                if (buffer.readByte() == StsConstants.LF) {
                    checkpoint(State.READ_CHUNK_SIZE);
                    return;
                }
            } else if (next == StsConstants.LF) {
                checkpoint(State.READ_CHUNK_SIZE);
                return;
            } else {
                checkpoint();
            }
        }
    }
    case READ_CHUNK_FOOTER:
        try {
            LastStsContent trailer = readTrailingHeaders(buffer);
            out.add(trailer);
            reset();
            return;
        } catch (Exception e) {
            out.add(invalidChunk(e));
            return;
        }
    case BAD_MESSAGE: {
        // Keep discarding until disconnection.
        buffer.skipBytes(actualReadableBytes());
        break;
    }
    case UPGRADED: {
        // Do not touch anything read - other handler will replace this codec with the upgraded protocol codec to
        // take the trafic over.
        break;
    }
    }
}

From source file:org.apache.activemq.artemis.tests.integration.transports.netty.ActiveMQFrameDecoder2Test.java

License:Apache License

@Test
public void testOrdinaryFragmentation() throws Exception {
    final EmbeddedChannel decoder = new EmbeddedChannel(new ActiveMQFrameDecoder2());
    final byte[] data = new byte[ActiveMQFrameDecoder2Test.MSG_LEN];
    ActiveMQFrameDecoder2Test.rand.nextBytes(data);

    ByteBuf src = Unpooled.buffer(ActiveMQFrameDecoder2Test.MSG_CNT * (ActiveMQFrameDecoder2Test.MSG_LEN + 4));
    while (src.writerIndex() < src.capacity()) {
        src.writeInt(ActiveMQFrameDecoder2Test.MSG_LEN);
        src.writeBytes(data);/*  ww  w  . j  a  va  2  s  .c o  m*/
    }

    List<ByteBuf> packets = new ArrayList<ByteBuf>();
    while (src.isReadable()) {
        int length = Math.min(
                ActiveMQFrameDecoder2Test.rand.nextInt(ActiveMQFrameDecoder2Test.FRAGMENT_MAX_LEN),
                src.readableBytes());
        packets.add(src.readBytes(length));
    }

    int cnt = 0;
    for (ByteBuf p : packets) {
        decoder.writeInbound(p);
        for (;;) {
            ByteBuf frame = (ByteBuf) decoder.readInbound();
            if (frame == null) {
                break;
            }
            Assert.assertEquals(4, frame.readerIndex());
            Assert.assertEquals(ActiveMQFrameDecoder2Test.MSG_LEN, frame.readableBytes());
            Assert.assertEquals(Unpooled.wrappedBuffer(data), frame);
            cnt++;
            frame.release();
        }
    }
    Assert.assertEquals(ActiveMQFrameDecoder2Test.MSG_CNT, cnt);
}

From source file:org.apache.bookkeeper.bookie.EntryLogger.java

License:Apache License

EntryLogMetadata extractEntryLogMetadataFromIndex(long entryLogId) throws IOException {
    Header header = getHeaderForLogId(entryLogId);

    if (header.version < HEADER_V1) {
        throw new IOException("Old log file header without ledgers map on entryLogId " + entryLogId);
    }/* w w  w.j a v a2 s . co  m*/

    if (header.ledgersMapOffset == 0L) {
        // The index was not stored in the log file (possibly because the bookie crashed before flushing it)
        throw new IOException("No ledgers map index found on entryLogId" + entryLogId);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Recovering ledgers maps for log {} at offset: {}", entryLogId, header.ledgersMapOffset);
    }

    BufferedReadChannel bc = getChannelForLogId(entryLogId);

    // There can be multiple entries containing the various components of the serialized ledgers map
    long offset = header.ledgersMapOffset;
    EntryLogMetadata meta = new EntryLogMetadata(entryLogId);

    final int maxMapSize = LEDGERS_MAP_HEADER_SIZE + LEDGERS_MAP_ENTRY_SIZE * LEDGERS_MAP_MAX_BATCH_SIZE;
    ByteBuf ledgersMap = allocator.directBuffer(maxMapSize);

    try {
        while (offset < bc.size()) {
            // Read ledgers map size
            sizeBuffer.get().clear();
            bc.read(sizeBuffer.get(), offset);

            int ledgersMapSize = sizeBuffer.get().readInt();

            // Read the index into a buffer
            ledgersMap.clear();
            bc.read(ledgersMap, offset + 4, ledgersMapSize);

            // Discard ledgerId and entryId
            long lid = ledgersMap.readLong();
            if (lid != INVALID_LID) {
                throw new IOException("Cannot deserialize ledgers map from ledger " + lid);
            }

            long entryId = ledgersMap.readLong();
            if (entryId != LEDGERS_MAP_ENTRY_ID) {
                throw new IOException("Cannot deserialize ledgers map from entryId " + entryId);
            }

            // Read the number of ledgers in the current entry batch
            int ledgersCount = ledgersMap.readInt();

            // Extract all (ledger,size) tuples from buffer
            for (int i = 0; i < ledgersCount; i++) {
                long ledgerId = ledgersMap.readLong();
                long size = ledgersMap.readLong();

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Recovering ledgers maps for log {} -- Found ledger: {} with size: {}",
                            entryLogId, ledgerId, size);
                }
                meta.addLedgerSize(ledgerId, size);
            }
            if (ledgersMap.isReadable()) {
                throw new IOException("Invalid entry size when reading ledgers map");
            }

            // Move to next entry, if any
            offset += ledgersMapSize + 4;
        }
    } catch (IndexOutOfBoundsException e) {
        throw new IOException(e);
    } finally {
        ledgersMap.release();
    }

    if (meta.getLedgersMap().size() != header.ledgersCount) {
        throw new IOException(
                "Not all ledgers were found in ledgers map index. expected: " + header.ledgersCount
                        + " -- found: " + meta.getLedgersMap().size() + " -- entryLogId: " + entryLogId);
    }

    return meta;
}