Example usage for io.netty.handler.codec.http HttpHeaders isContentLengthSet

List of usage examples for io.netty.handler.codec.http HttpHeaders isContentLengthSet

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpHeaders isContentLengthSet.

Prototype

@Deprecated
public static boolean isContentLengthSet(HttpMessage m) 

Source Link

Usage

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

@Override
public Future<Long> write(ByteBuffer src, Callback<Long> callback) {
    long writeProcessingStartTime = System.currentTimeMillis();
    if (!responseMetadataWriteInitiated.get()) {
        maybeWriteResponseMetadata(responseMetadata, new ResponseMetadataWriteListener());
    }//from w ww .j av  a 2s.c  o m
    Chunk chunk = new Chunk(src, callback);
    chunksToWrite.add(chunk);
    if (!isOpen()) {
        // the isOpen() check is not before addition to the queue because chunks need to be acknowledged in the order
        // they were received. If we don't add it to the queue and clean up, chunks may be acknowledged out of order.
        logger.debug("Scheduling a chunk cleanup on channel {} because response channel is closed",
                ctx.channel());
        writeFuture.addListener(new CleanupCallback(new ClosedChannelException()));
    } else if (finalResponseMetadata instanceof FullHttpResponse) {
        logger.debug("Scheduling a chunk cleanup on channel {} because Content-Length is 0", ctx.channel());
        Exception exception = null;
        // this is only allowed to be a 0 sized buffer.
        if (src.remaining() > 0) {
            exception = new IllegalStateException(
                    "Provided non zero size content after setting Content-Length to 0");
            if (!writeFuture.isDone()) {
                writeFuture.setFailure(exception);
            }
        }
        writeFuture.addListener(new CleanupCallback(exception));
    } else if (HttpHeaders.isContentLengthSet(finalResponseMetadata)
            && totalBytesReceived.get() > HttpHeaders.getContentLength(finalResponseMetadata)) {
        Exception exception = new IllegalStateException("Size of provided content [" + totalBytesReceived.get()
                + "] is greater than Content-Length set [" + HttpHeaders.getContentLength(finalResponseMetadata)
                + "]");
        if (!writeFuture.isDone()) {
            writeFuture.setFailure(exception);
        }
        writeFuture.addListener(new CleanupCallback(exception));
    } else {
        chunkedWriteHandler.resumeTransfer();
    }

    long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
    nettyMetrics.writeProcessingTimeInMs.update(writeProcessingTime);
    if (request != null) {
        request.getMetricsTracker().nioMetricsTracker.addToResponseProcessingTime(writeProcessingTime);
    }
    return chunk.future;
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Writes response metadata to the channel if not already written previously and channel is active.
 * @param responseMetadata the {@link HttpResponse} that needs to be written.
 * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
 * @return {@code true} if response metadata was written to the channel in this call. {@code false} otherwise.
 *///from  w  ww.j  a v a 2  s .com
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
        GenericFutureListener<ChannelFuture> listener) {
    long writeProcessingStartTime = System.currentTimeMillis();
    boolean writtenThisTime = false;
    if (responseMetadataWriteInitiated.compareAndSet(false, true) && ctx.channel().isActive()) {
        // we do some manipulation here for chunking. According to the HTTP spec, we can have either a Content-Length
        // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not there, we add
        // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just explicitly specifying
        // this in the header.
        if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
            // This makes sure that we don't stomp on any existing transfer-encoding.
            HttpHeaders.setTransferEncodingChunked(responseMetadata);
        } else if (HttpHeaders.getContentLength(responseMetadata) == 0
                && !(responseMetadata instanceof FullHttpResponse)) {
            // if the Content-Length is 0, we can send a FullHttpResponse since there is no content expected.
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    responseMetadata.getStatus());
            fullHttpResponse.headers().set(responseMetadata.headers());
            responseMetadata = fullHttpResponse;
        }
        logger.trace("Sending response with status {} on channel {}", responseMetadata.getStatus(),
                ctx.channel());
        finalResponseMetadata = responseMetadata;
        ChannelPromise writePromise = ctx.newPromise().addListener(listener);
        ctx.writeAndFlush(responseMetadata, writePromise);
        writtenThisTime = true;
        long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
        nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
    }
    return writtenThisTime;
}

From source file:com.github.ambry.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Writes response metadata to the channel if not already written previously and channel is active.
 * @param responseMetadata the {@link HttpResponse} that needs to be written.
 * @param listener the {@link GenericFutureListener} that needs to be attached to the write.
 * @return {@code true} if response metadata was written to the channel in this call. {@code false} otherwise.
 *//* w ww  . ja va 2  s .co m*/
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
        GenericFutureListener<ChannelFuture> listener) {
    long writeProcessingStartTime = System.currentTimeMillis();
    boolean writtenThisTime = false;
    if (responseMetadataWritten.compareAndSet(false, true)) {
        // we do some manipulation here for chunking. According to the HTTP spec, we can have either a Content-Length
        // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not there, we add
        // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just explicitly specifying
        // this in the header.
        if (!HttpHeaders.isContentLengthSet(responseMetadata)) {
            // This makes sure that we don't stomp on any existing transfer-encoding.
            HttpHeaders.setTransferEncodingChunked(responseMetadata);
        }
        logger.trace("Sending response with status {} on channel {}", responseMetadata.getStatus(),
                ctx.channel());
        ChannelPromise writePromise = ctx.newPromise().addListener(listener);
        ctx.writeAndFlush(responseMetadata, writePromise);
        writtenThisTime = true;
        long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime;
        nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime);
    }
    return writtenThisTime;
}

From source file:com.titilink.camel.rest.client.HttpClientHandler.java

License:LGPL

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    //?/* w w w.j  av a 2  s  .com*/
    boolean isReadOverMsg = false;
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;
        if (HttpHeaders.isContentLengthSet(response)) {
            int pkLength = (int) HttpHeaders.getContentLength(response);
            if (pkLength > maxPacketSize) {
                LOGGER.error(
                        "http response packet size exceeds the system limit threshold, realSize={},maxPacketSize={}.",
                        new Object[] { pkLength, maxPacketSize });
                isOverSizePackage = true;
            } else {
                isOverSizePackage = false;
            }
        }
        LOGGER.debug("status: {} , version: {}", response.getStatus(), response.getProtocolVersion());
        if (firstHeader) {
            // ???500??
            Status status = isOverSizePackage ? Status.SERVER_ERROR_INTERNAL
                    : Status.valueOf(((HttpResponse) msg).getStatus().code());
            result = new RestResponse(status);
            if (isOverSizePackage) {
                //??
                result.setText("{\"code\":\"" + HTTP_DOWN_PACKAGE_SIZE_OVER
                        + "\",\"message\":\"http response packet size exceeds the system limit threshold\"}");
            }
            firstHeader = false;
        }
        if (!response.headers().isEmpty()) {
            for (String name : response.headers().names()) {
                for (String value : response.headers().getAll(name)) {
                    result.addHeader(name, value);
                }
            }
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        //????contentBufBuilder?
        if (!isOverSizePackage) {
            String sContent = content.content().toString(CharsetUtil.UTF_8);
            contentBufBuilder.append(sContent);
            if (content instanceof LastHttpContent) {
                if (null != result && HttpResponseStatus.NO_CONTENT.code() != result.getStatus().getCode()) {
                    result.setText(contentBufBuilder.toString());
                }
                isReadOverMsg = true;
            }
        }
    }
    /**
     * ?  ??result
     */
    if ((!isReadOverMsg && isOverSizePackage) || (isReadOverMsg && !isOverSizePackage)) {
        if (!queue.offer(result)) {
            LOGGER.error("channelRead0. add result to queue failed");
        }
        reset();
    }
}

From source file:com.twitter.http2.HttpStreamDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    if (msg instanceof HttpHeadersFrame) {

        HttpHeadersFrame httpHeadersFrame = (HttpHeadersFrame) msg;
        int streamId = httpHeadersFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        if (message == null) {
            if (httpHeadersFrame.headers().contains(":status")) {

                // If a client receives a reply with a truncated header block,
                // reply with a RST_STREAM frame with error code INTERNAL_ERROR.
                if (httpHeadersFrame.isTruncated()) {
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.INTERNAL_ERROR);
                    out.add(httpRstStreamFrame);
                    return;
                }//w  ww  . ja  va  2s  .  c  o  m

                try {
                    StreamedHttpResponse response = createHttpResponse(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        HttpHeaders.setContentLength(response, 0);
                        response.getContent().close();
                    } else {
                        // Response body will follow in a series of Data Frames
                        if (!HttpHeaders.isContentLengthSet(response)) {
                            HttpHeaders.setTransferEncodingChunked(response);
                        }
                        messageMap.put(streamId, response);
                    }
                    out.add(response);
                } catch (Exception e) {
                    // If a client receives a SYN_REPLY without valid getStatus and version headers
                    // the client must reply with a RST_STREAM frame indicating a PROTOCOL_ERROR
                    HttpRstStreamFrame httpRstStreamFrame = new DefaultHttpRstStreamFrame(streamId,
                            HttpErrorCode.PROTOCOL_ERROR);
                    ctx.writeAndFlush(httpRstStreamFrame);
                    out.add(httpRstStreamFrame);
                }

            } else {

                // If a client sends a request with a truncated header block, the server must
                // reply with a HTTP 431 REQUEST HEADER FIELDS TOO LARGE reply.
                if (httpHeadersFrame.isTruncated()) {
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status",
                            HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                    return;
                }

                try {
                    message = createHttpRequest(httpHeadersFrame);

                    if (httpHeadersFrame.isLast()) {
                        message.setDecoderResult(DecoderResult.SUCCESS);
                        message.getContent().close();
                    } else {
                        // Request body will follow in a series of Data Frames
                        messageMap.put(streamId, message);
                    }

                    out.add(message);

                } catch (Exception e) {
                    // If a client sends a SYN_STREAM without all of the method, url (host and path),
                    // scheme, and version headers the server must reply with a HTTP 400 BAD REQUEST reply.
                    // Also sends HTTP 400 BAD REQUEST reply if header name/value pairs are invalid
                    httpHeadersFrame = new DefaultHttpHeadersFrame(streamId);
                    httpHeadersFrame.setLast(true);
                    httpHeadersFrame.headers().set(":status", HttpResponseStatus.BAD_REQUEST.code());
                    ctx.writeAndFlush(httpHeadersFrame);
                }
            }
        } else {
            LastHttpContent trailer = trailerMap.remove(streamId);
            if (trailer == null) {
                trailer = new DefaultLastHttpContent();
            }

            // Ignore trailers in a truncated HEADERS frame.
            if (!httpHeadersFrame.isTruncated()) {
                for (Map.Entry<String, String> e : httpHeadersFrame.headers()) {
                    trailer.trailingHeaders().add(e.getKey(), e.getValue());
                }
            }

            if (httpHeadersFrame.isLast()) {
                messageMap.remove(streamId);
                message.addContent(trailer);
            } else {
                trailerMap.put(streamId, trailer);
            }
        }

    } else if (msg instanceof HttpDataFrame) {

        HttpDataFrame httpDataFrame = (HttpDataFrame) msg;
        int streamId = httpDataFrame.getStreamId();
        StreamedHttpMessage message = messageMap.get(streamId);

        // If message is not in map discard Data Frame.
        if (message == null) {
            return;
        }

        ByteBuf content = httpDataFrame.content();
        if (content.isReadable()) {
            content.retain();
            message.addContent(new DefaultHttpContent(content));
        }

        if (httpDataFrame.isLast()) {
            messageMap.remove(streamId);
            message.addContent(LastHttpContent.EMPTY_LAST_CONTENT);
            message.setDecoderResult(DecoderResult.SUCCESS);
        }

    } else if (msg instanceof HttpRstStreamFrame) {

        HttpRstStreamFrame httpRstStreamFrame = (HttpRstStreamFrame) msg;
        int streamId = httpRstStreamFrame.getStreamId();
        StreamedHttpMessage message = messageMap.remove(streamId);

        if (message != null) {
            message.getContent().close();
            message.setDecoderResult(DecoderResult.failure(CANCELLATION_EXCEPTION));
        }

    } else {
        // HttpGoAwayFrame
        out.add(msg);
    }
}

From source file:io.reactivex.netty.protocol.http.client.HttpRequestHeaders.java

License:Apache License

public boolean isContentLengthSet() {
    return HttpHeaders.isContentLengthSet(nettyRequest);
}

From source file:io.reactivex.netty.protocol.http.client.HttpResponseHeaders.java

License:Apache License

public boolean isContentLengthSet() {
    return HttpHeaders.isContentLengthSet(nettyResponse);
}

From source file:org.springframework.boot.context.embedded.netty.HttpResponseOutputStream.java

License:Apache License

private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    if (!HttpHeaders.isContentLengthSet(response)) {
        if (lastContent) {
            HttpHeaders.setContentLength(response, count);
        } else {//ww w  .  j a v  a2  s.  c o m
            HttpHeaders.setTransferEncodingChunked(response);
        }
    }
    ctx.write(response, ctx.voidPromise());
}