Example usage for io.netty.buffer CompositeByteBuf readableBytes

List of usage examples for io.netty.buffer CompositeByteBuf readableBytes

Introduction

In this page you can find the example usage for io.netty.buffer CompositeByteBuf readableBytes.

Prototype

@Override
    public int readableBytes() 

Source Link

Usage

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;//w  w w. j  a  v  a  2s.  c o m
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    FullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;//from   ww w  . j  a  va2 s.c o  m
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        // TODO: Respond with 413 Request Entity Too Large
        //   and discard the traffic or close the connection.
        //       No need to notify the upstream handlers - just log.
        //       If decoding a response, just throw an exception.
        if (is100ContinueExpected(m)) {
            ByteBuf buf = CONTINUE_LINE.duplicate();
            buf.retain();
            ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new DefaultFullHttpRequest(header.getProtocolVersion(),
                    header.getMethod(), header.getUri(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new DefaultFullHttpResponse(header.getProtocolVersion(),
                    header.getStatus(), Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else {
            throw new Error();
        }

        currentMessage.headers().set(m.headers());

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.headers().add(trailer.trailingHeaders());
            }

            // Set the 'Content-Length' header.
            currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(content.readableBytes()));

            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

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

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, StsObject msg, List<Object> out) throws Exception {
    FullStsMessage currentMessage = this.currentMessage;

    if (msg instanceof StsMessage) {
        tooLongFrameFound = false;/*from w  w w .j  a  v  a 2  s .co m*/
        assert currentMessage == null;

        StsMessage m = (StsMessage) msg;

        if (!m.getDecoderResult().isSuccess()) {
            this.currentMessage = null;
            out.add(ReferenceCountUtil.retain(m));
            return;
        }
        if (msg instanceof StsRequest) {
            StsRequest header = (StsRequest) msg;
            this.currentMessage = currentMessage = new DefaultFullStsRequest(header.getProtocolVersion(),
                    header.getMethod(), header.getUri(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else if (msg instanceof StsResponse) {
            StsResponse header = (StsResponse) msg;
            this.currentMessage = currentMessage = new DefaultFullStsResponse(header.getStatus(),
                    Unpooled.compositeBuffer(maxCumulationBufferComponents));
        } else {
            throw new Error();
        }

        currentMessage.headers().set(m.headers());
    } else if (msg instanceof StsContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastStsContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        StsContent chunk = (StsContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastStsContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastStsContent) {
                LastStsContent trailer = (LastStsContent) chunk;
                currentMessage.headers().add(trailer.trailingHeaders());
            }

            // Set the 'Content-Length' header.
            currentMessage.headers().set(StsHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(content.readableBytes()));

            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}

From source file:org.apache.helix.ipc.netty.NettyHelixIPCService.java

License:Apache License

/**
 * Sends a message to all partitions with a given state in the cluster.
 *///from   www. j  a  v  a2 s . co m
@Override
public void send(HelixAddress destination, int messageType, UUID messageId, ByteBuf message) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Sending " + messageId);
    }
    // Send message
    try {
        // Get list of channels
        List<Channel> channels = channelMap.get(destination.getSocketAddress());
        if (channels == null) {
            synchronized (channelMap) {
                channels = channelMap.get(destination.getSocketAddress());
                if (channels == null) {
                    channels = new ArrayList<Channel>(config.getNumConnections());
                    for (int i = 0; i < config.getNumConnections(); i++) {
                        channels.add(null);
                    }
                    channelMap.put(destination.getSocketAddress(), channels);
                }
            }
        }

        // Pick the channel for this scope
        int idx = (Integer.MAX_VALUE & destination.getScope().hashCode()) % channels.size();
        Channel channel = channels.get(idx);
        if (channel == null || !channel.isOpen()) {
            synchronized (channelMap) {
                channel = channels.get(idx);
                if (channel == null || !channel.isOpen()) {
                    channel = clientBootstrap.connect(destination.getSocketAddress()).sync().channel();
                    channels.set(idx, channel);
                    statChannelOpen.inc();
                }
            }
        }

        // Compute total length
        int headerLength = NUM_LENGTH_FIELDS * (Integer.SIZE / 8) + (Integer.SIZE / 8) * 2 // version, type
                + (Long.SIZE / 8) * 2 // 128 bit UUID
                + getLength(destination.getScope().getCluster())
                + getLength(destination.getScope().getResource())
                + getLength(destination.getScope().getPartition())
                + getLength(destination.getScope().getState()) + getLength(config.getInstanceName())
                + getLength(destination.getInstanceName());
        int messageLength = message == null ? 0 : message.readableBytes();

        // Build message header
        ByteBuf headerBuf = channel.alloc().buffer(headerLength);
        headerBuf.writeInt(MESSAGE_VERSION).writeInt(messageType).writeLong(messageId.getMostSignificantBits())
                .writeLong(messageId.getLeastSignificantBits());
        writeStringWithLength(headerBuf, destination.getScope().getCluster());
        writeStringWithLength(headerBuf, destination.getScope().getResource());
        writeStringWithLength(headerBuf, destination.getScope().getPartition());
        writeStringWithLength(headerBuf, destination.getScope().getState());
        writeStringWithLength(headerBuf, config.getInstanceName());
        writeStringWithLength(headerBuf, destination.getInstanceName());

        // Compose message header and payload
        headerBuf.writeInt(messageLength);
        CompositeByteBuf fullByteBuf = channel.alloc().compositeBuffer(2);
        fullByteBuf.addComponent(headerBuf);
        fullByteBuf.writerIndex(headerBuf.readableBytes());
        if (message != null) {
            fullByteBuf.addComponent(message);
            fullByteBuf.writerIndex(fullByteBuf.writerIndex() + message.readableBytes());
        }

        // Send
        NettyHelixIPCBackPressureHandler backPressureHandler = channel.pipeline()
                .get(NettyHelixIPCBackPressureHandler.class);
        backPressureHandler.waitUntilWritable(channel);
        channel.writeAndFlush(fullByteBuf);

        statTxMsg.mark();
        statTxBytes.mark(fullByteBuf.readableBytes());
    } catch (Exception e) {
        statError.inc();
        throw new IllegalStateException("Could not send message to " + destination, e);
    }
}