Java Code Examples for io.netty.handler.codec.http.HttpUtil#isContentLengthSet()

The following examples show how to use io.netty.handler.codec.http.HttpUtil#isContentLengthSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpStreamsClientHandler.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean hasBody(HttpResponse response) {
    if (response.status().code() >= 100 && response.status().code() < 200) {
        return false;
    }

    if (response.status().equals(HttpResponseStatus.NO_CONTENT) ||
        response.status().equals(HttpResponseStatus.NOT_MODIFIED)) {
        return false;
    }

    if (HttpUtil.isTransferEncodingChunked(response)) {
        return true;
    }


    if (HttpUtil.isContentLengthSet(response)) {
        return HttpUtil.getContentLength(response) > 0;
    }

    return true;
}
 
Example 2
Source File: HttpOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
public final NettyOutbound sendFile(Path file, long position, long count) {
	Objects.requireNonNull(file);

	if (hasSentHeaders()) {
		return super.sendFile(file, position, count);
	}

	if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage()) && !HttpUtil.isContentLengthSet(
			outboundHttpMessage()) && count < Integer.MAX_VALUE) {
		outboundHttpMessage().headers()
		                     .setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count);
	}
	else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) {
		outboundHttpMessage().headers()
		                     .remove(HttpHeaderNames.CONTENT_LENGTH)
		                     .remove(HttpHeaderNames.TRANSFER_ENCODING);
		HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
	}

	return super.sendFile(file, position, count);
}
 
Example 3
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Method to easily create a request.
 * @param httpMethod the {@link HttpMethod} desired.
 * @param uri string representation of the desired URI.
 * @param headers any associated headers as a {@link HttpHeaders} object. Can be null.
 * @param content the content that accompanies the request. Can be null.
 * @return A {@link FullHttpRequest} object that defines the request required by the input.
 */
private FullHttpRequest buildRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, ByteBuffer content) {
  ByteBuf contentBuf;
  if (content != null) {
    contentBuf = Unpooled.wrappedBuffer(content);
  } else {
    contentBuf = Unpooled.buffer(0);
  }
  FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, contentBuf);
  if (headers != null) {
    httpRequest.headers().set(headers);
  }
  if (HttpMethod.POST.equals(httpMethod) && !HttpUtil.isContentLengthSet(httpRequest)) {
    HttpUtil.setTransferEncodingChunked(httpRequest, true);
  }
  return httpRequest;
}
 
Example 4
Source File: HttpResponseOutputStream.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
private void writeResponse(boolean lastContent) {
    HttpResponse response = servletResponse.getNettyResponse();
    // TODO implement exceptions required by http://tools.ietf.org/html/rfc2616#section-4.4
    // 设置content-length头
    if (!HttpUtil.isContentLengthSet(response)) {
        HttpUtil.setContentLength(response, totalLength);
    }
    ctx.write(response, ctx.voidPromise());
}
 
Example 5
Source File: RoutingHandler.java    From riposte with Apache License 2.0 5 votes vote down vote up
private void throwExceptionIfContentLengthHeaderIsLargerThanConfiguredMaxRequestSize(HttpRequest msg, Endpoint<?> endpoint) {
    int configuredMaxRequestSize = getConfiguredMaxRequestSize(endpoint, globalConfiguredMaxRequestSizeInBytes);

    if (!isMaxRequestSizeValidationDisabled(configuredMaxRequestSize)
        && HttpUtil.isContentLengthSet(msg)
        && HttpUtil.getContentLength(msg) > configuredMaxRequestSize
    ) {
        throw new RequestTooBigException(
            "Content-Length header value exceeded configured max request size of " + configuredMaxRequestSize
        );
    }
}
 
Example 6
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
 */
private boolean maybeWriteResponseMetadata(HttpResponse responseMetadata,
    GenericFutureListener<ChannelFuture> listener) {
  long writeProcessingStartTime = System.currentTimeMillis();
  boolean writtenThisTime = false;
  if (ctx.channel().isActive() && responseMetadataWriteInitiated.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 on 200 response. Note that sending HttpContent chunks data anyway - we are just
    // explicitly specifying this in the header.
    if (!HttpUtil.isContentLengthSet(responseMetadata) && (responseMetadata.status().equals(HttpResponseStatus.OK)
        || responseMetadata.status().equals(HttpResponseStatus.PARTIAL_CONTENT))) {
      // This makes sure that we don't stomp on any existing transfer-encoding.
      HttpUtil.setTransferEncodingChunked(responseMetadata, true);
    } else if (HttpUtil.isContentLengthSet(responseMetadata) && HttpUtil.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.status());
      fullHttpResponse.headers().set(responseMetadata.headers());
      responseMetadata = fullHttpResponse;
    }
    logger.trace("Sending response with status {} on channel {}", responseMetadata.status(), 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);
    if (request != null) {
      request.getMetricsTracker().nioMetricsTracker.markFirstByteSent();
    }
  }
  return writtenThisTime;
}
 
Example 7
Source File: Http2StreamFrameToHttpObjectCodec.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, Http2StreamFrame frame, List<Object> out) throws Exception {
    if (frame instanceof Http2HeadersFrame) {
        int id = 0; // not really the id
        Http2HeadersFrame headersFrame = (Http2HeadersFrame) frame;
        Http2Headers headers = headersFrame.headers();

        final CharSequence status = headers.status();

        // 100-continue response is a special case where Http2HeadersFrame#isEndStream=false
        // but we need to decode it as a FullHttpResponse to play nice with HttpObjectAggregator.
        if (null != status && HttpResponseStatus.CONTINUE.codeAsText().contentEquals(status)) {
            final FullHttpMessage fullMsg = newFullMessage(id, headers, ctx.alloc());
            out.add(fullMsg);
            return;
        }

        if (headersFrame.isEndStream()) {
            if (headers.method() == null && status == null) {
                LastHttpContent last = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, validateHeaders);
                HttpConversionUtil.addHttp2ToHttpHeaders(id, headers, last.trailingHeaders(),
                                                         HttpVersion.HTTP_1_1, true, true);
                out.add(last);
            } else {
                FullHttpMessage full = newFullMessage(id, headers, ctx.alloc());
                out.add(full);
            }
        } else {
            HttpMessage req = newMessage(id, headers);
            if (!HttpUtil.isContentLengthSet(req)) {
                req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
            }
            out.add(req);
        }
    } else if (frame instanceof Http2DataFrame) {
        Http2DataFrame dataFrame = (Http2DataFrame) frame;
        if (dataFrame.isEndStream()) {
            out.add(new DefaultLastHttpContent(dataFrame.content().retain(), validateHeaders));
        } else {
            out.add(new DefaultHttpContent(dataFrame.content().retain()));
        }
    }
}
 
Example 8
Source File: ClientResponseWriter.java    From zuul with Apache License 2.0 4 votes vote down vote up
private HttpResponse buildHttpResponse(final HttpResponseMessage zuulResp) {
    final HttpRequestInfo zuulRequest = zuulResp.getInboundRequest();
    HttpVersion responseHttpVersion;
    final String inboundProtocol = zuulRequest.getProtocol();
    if (inboundProtocol.startsWith("HTTP/1")) {
        responseHttpVersion = HttpVersion.valueOf(inboundProtocol);
    }
    else {
        // Default to 1.1. We do this to cope with HTTP/2 inbound requests.
        responseHttpVersion = HttpVersion.HTTP_1_1;
    }

    // Create the main http response to send, with body.
    final DefaultHttpResponse nativeResponse = new DefaultHttpResponse(responseHttpVersion,
            HttpResponseStatus.valueOf(zuulResp.getStatus()), false, false);

    // Now set all of the response headers - note this is a multi-set in keeping with HTTP semantics
    final HttpHeaders nativeHeaders = nativeResponse.headers();
    for (Header entry : zuulResp.getHeaders().entries()) {
        nativeHeaders.add(entry.getKey(), entry.getValue());
    }

    // Netty does not automatically add Content-Length or Transfer-Encoding: chunked. So we add here if missing.
    if (! HttpUtil.isContentLengthSet(nativeResponse) && ! HttpUtil.isTransferEncodingChunked(nativeResponse)) {
        nativeResponse.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    }

    final HttpRequest nativeReq = (HttpRequest) zuulResp.getContext().get(CommonContextKeys.NETTY_HTTP_REQUEST);
    if (!closeConnection && HttpUtil.isKeepAlive(nativeReq)) {
        HttpUtil.setKeepAlive(nativeResponse, true);
    } else {
        // Send a Connection: close response header (only needed for HTTP/1.0 but no harm in doing for 1.1 too).
        nativeResponse.headers().set("Connection", "close");
    }

    // TODO - temp hack for http/2 handling.
    if (nativeReq.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) {
        String streamId = nativeReq.headers().get(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        nativeResponse.headers().set(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId);
    }

    return nativeResponse;
}