Search in sources :

Example 91 with LastHttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent in project riposte by Nike-Inc.

the class RequestInfoImplTest method addContentChunk_throws_IllegalStateException_if_requestInfo_trailingHeaders_is_already_populated_when_last_chunk_arrives.

@Test(expected = IllegalStateException.class)
public void addContentChunk_throws_IllegalStateException_if_requestInfo_trailingHeaders_is_already_populated_when_last_chunk_arrives() {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    LastHttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));
    requestInfo.trailingHeaders.add("somekey", "someval");
    // expect
    requestInfo.addContentChunk(lastChunk);
    fail("Expected an IllegalStateException, but no exception was thrown");
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 92 with LastHttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent in project riposte by Nike-Inc.

the class RequestInfoImplTest method uber_constructor_works_for_valid_values.

@Test
public void uber_constructor_works_for_valid_values() {
    // given
    String uri = "/some/uri/path/%24foobar%26?notused=blah";
    HttpMethod method = HttpMethod.PATCH;
    Charset contentCharset = CharsetUtil.US_ASCII;
    HttpHeaders headers = new DefaultHttpHeaders().add("header1", "val1").add(HttpHeaders.Names.CONTENT_TYPE, "text/text charset=" + contentCharset.displayName());
    QueryStringDecoder queryParams = new QueryStringDecoder(uri + "?foo=bar&secondparam=secondvalue");
    Set<Cookie> cookies = new HashSet<>(Arrays.asList(new DefaultCookie("cookie1", "val1"), new DefaultCookie("cookie2", "val2")));
    Map<String, String> pathParams = Arrays.stream(new String[][] { { "pathParam1", "val1" }, { "pathParam2", "val2" } }).collect(Collectors.toMap(pair -> pair[0], pair -> pair[1]));
    String content = UUID.randomUUID().toString();
    byte[] contentBytes = content.getBytes();
    LastHttpContent chunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(contentBytes));
    chunk.trailingHeaders().add("trailingHeader1", "trailingVal1");
    List<HttpContent> contentChunks = Collections.singletonList(chunk);
    HttpVersion protocolVersion = HttpVersion.HTTP_1_1;
    boolean keepAlive = true;
    boolean fullRequest = true;
    boolean isMultipart = false;
    // when
    RequestInfoImpl<?> requestInfo = new RequestInfoImpl<>(uri, method, headers, chunk.trailingHeaders(), queryParams, cookies, pathParams, contentChunks, protocolVersion, keepAlive, fullRequest, isMultipart);
    // then
    assertThat("getUri should return passed in value", requestInfo.getUri(), is(uri));
    assertThat("getPath did not decode as expected", requestInfo.getPath(), is("/some/uri/path/$foobar&"));
    assertThat(requestInfo.getMethod(), is(method));
    assertThat(requestInfo.getHeaders(), is(headers));
    assertThat(requestInfo.getTrailingHeaders(), is(chunk.trailingHeaders()));
    assertThat(requestInfo.getQueryParams(), is(queryParams));
    assertThat(requestInfo.getCookies(), is(cookies));
    assertThat(requestInfo.pathTemplate, nullValue());
    assertThat(requestInfo.pathParams, is(pathParams));
    assertThat(requestInfo.getRawContentBytes(), is(contentBytes));
    assertThat(requestInfo.getRawContent(), is(content));
    assertThat(requestInfo.content, nullValue());
    assertThat(requestInfo.getContentCharset(), is(contentCharset));
    assertThat(requestInfo.getProtocolVersion(), is(protocolVersion));
    assertThat(requestInfo.isKeepAliveRequested(), is(keepAlive));
    assertThat(requestInfo.isCompleteRequestWithAllChunks, is(fullRequest));
    assertThat(requestInfo.isMultipart, is(isMultipart));
}
Also used : Cookie(io.netty.handler.codec.http.cookie.Cookie) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Arrays(java.util.Arrays) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) Unpooled(io.netty.buffer.Unpooled) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Mockito.doThrow(org.mockito.Mockito.doThrow) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) CharsetUtil(io.netty.util.CharsetUtil) Assertions(org.assertj.core.api.Assertions) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Mockito.doReturn(org.mockito.Mockito.doReturn) RequestContentDeserializationException(com.nike.riposte.server.error.exception.RequestContentDeserializationException) Set(java.util.Set) UUID(java.util.UUID) Cookie(io.netty.handler.codec.http.cookie.Cookie) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) Collectors(java.util.stream.Collectors) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Sets(com.google.common.collect.Sets) List(java.util.List) Type(java.lang.reflect.Type) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) HttpPostMultipartRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostMultipartRequestDecoder) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RequestInfo(com.nike.riposte.server.http.RequestInfo) HttpVersion(io.netty.handler.codec.http.HttpVersion) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) DataProvider(com.tngtech.java.junit.dataprovider.DataProvider) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) ClientCookieEncoder(io.netty.handler.codec.http.cookie.ClientCookieEncoder) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) PathParameterMatchingException(com.nike.riposte.server.error.exception.PathParameterMatchingException) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Whitebox(com.nike.riposte.testutils.Whitebox) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) CoreMatchers.sameInstance(org.hamcrest.CoreMatchers.sameInstance) HttpContent(io.netty.handler.codec.http.HttpContent) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TestCase.fail(junit.framework.TestCase.fail) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) IOException(java.io.IOException) Mockito.verify(org.mockito.Mockito.verify) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) Mockito.never(org.mockito.Mockito.never) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) Pair(com.nike.internal.util.Pair) Collections(java.util.Collections) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Charset(java.nio.charset.Charset) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DefaultCookie(io.netty.handler.codec.http.cookie.DefaultCookie) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 93 with LastHttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent in project riposte by Nike-Inc.

the class RequestInfoImplTest method addContentChunk_adds_last_chunk_trailing_headers.

@Test
public void addContentChunk_adds_last_chunk_trailing_headers() {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    LastHttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));
    String headerKey = UUID.randomUUID().toString();
    List<String> headerVal = Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    lastChunk.trailingHeaders().add(headerKey, headerVal);
    // when
    requestInfo.addContentChunk(lastChunk);
    // then
    assertThat(requestInfo.trailingHeaders.names().size(), is(1));
    assertThat(requestInfo.trailingHeaders.getAll(headerKey), is(headerVal));
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 94 with LastHttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent in project riposte by Nike-Inc.

the class RequestInfoImplTest method addContentChunk_does_not_set_isCompleteRequestWithAllChunks_to_true_if_contentChunksWillBeReleasedExternally_is_true.

@Test
public void addContentChunk_does_not_set_isCompleteRequestWithAllChunks_to_true_if_contentChunksWillBeReleasedExternally_is_true() {
    // given
    RequestInfoImpl<?> requestInfo = RequestInfoImpl.dummyInstanceForUnknownRequests();
    requestInfo.isCompleteRequestWithAllChunks = false;
    requestInfo.contentChunksWillBeReleasedExternally();
    LastHttpContent lastChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));
    // when
    requestInfo.addContentChunk(lastChunk);
    // then
    Assertions.assertThat(requestInfo.isCompleteRequestWithAllChunks()).isFalse();
    Assertions.assertThat(requestInfo.contentChunks).isEmpty();
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 95 with LastHttpContent

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent in project riposte by Nike-Inc.

the class ResponseSender method writeChunk.

protected void writeChunk(ChannelHandlerContext ctx, HttpObject chunkToWrite, RequestInfo requestInfo, ResponseInfo<?> responseInfo, HttpProcessingState state) {
    boolean chunkIsInitialHttpResponse = chunkToWrite instanceof HttpResponse;
    boolean chunkIsPayloadContent = chunkToWrite instanceof HttpContent;
    boolean isLastChunk = chunkToWrite instanceof LastHttpContent;
    if (responseInfo.getUncompressedRawContentLength() == null) {
        // This is the first chunk being sent for this response. Initialize the uncompressed raw content length
        // value to 0 so we can add to it as we find content.
        responseInfo.setUncompressedRawContentLength(0L);
    }
    // Add to responseInfo's uncompressed content length value if appropriate
    if (chunkIsPayloadContent) {
        ByteBuf actualContent = ((HttpContent) chunkToWrite).content();
        if (actualContent != null) {
            long newUncompressedRawContentLengthValue = responseInfo.getUncompressedRawContentLength() + actualContent.readableBytes();
            responseInfo.setUncompressedRawContentLength(newUncompressedRawContentLengthValue);
        }
    }
    // (or finished).
    if (state != null) {
        // Update the ResponseInfo to indicate that the response sending has been started if this is the first chunk
        if (chunkIsInitialHttpResponse) {
            responseInfo.setResponseSendingStarted(true);
        }
        // Update ResponseInfo to indicate that the last chunk has been sent if this is the last chunk.
        if (isLastChunk) {
            responseInfo.setResponseSendingLastChunkSent(true);
        }
    }
    // Debog-log the chunk.
    if (chunkIsInitialHttpResponse) {
        logResponseFirstChunk((HttpResponse) chunkToWrite, ctx);
    } else if (chunkIsPayloadContent) {
        logResponseContentChunk((HttpContent) chunkToWrite, ctx);
    } else {
        throw new IllegalStateException("What is this?: " + chunkToWrite.getClass().getName());
    }
    if (chunkIsInitialHttpResponse && state != null) {
        // This is the first bytes of the response, and the state's ResponseInfo has been updated with the final
        // response data (like HTTP response status code), so we want to handle the response tagging on the
        // overall-request distributed tracing span, and set final span name.
        state.handleTracingResponseTaggingAndFinalSpanNameIfNotAlreadyDone();
        // We also want to set the wire-send annotation on the span.
        Span overallRequestSpan = state.getOverallRequestSpan();
        if (overallRequestSpan != null && spanNamingAndTaggingStrategy.shouldAddWireSendStartAnnotation()) {
            overallRequestSpan.addTimestampedAnnotationForCurrentTime(spanNamingAndTaggingStrategy.wireSendStartAnnotationName());
        }
    }
    // Write the response, which will send it through the outbound pipeline
    // (where it might be modified by outbound handlers).
    ChannelFuture writeFuture = ctx.write(chunkToWrite);
    // Handle state-related bookkeeping
    if (state != null && isLastChunk) {
        // Set the state's responseWriterFinalChunkChannelFuture so that handlers can hook into it if desired.
        state.setResponseWriterFinalChunkChannelFuture(writeFuture);
        // Always attach a listener that sets response end time, and adds a "we sent the last bytes of the
        // response on the wire" annotation to the overall request span.
        writeFuture.addListener(future -> {
            state.setResponseEndTimeNanosToNowIfNotAlreadySet();
            Span overallRequestSpan = state.getOverallRequestSpan();
            if (overallRequestSpan != null && spanNamingAndTaggingStrategy.shouldAddWireSendFinishAnnotation()) {
                overallRequestSpan.addTimestampedAnnotationForCurrentTime(spanNamingAndTaggingStrategy.wireSendFinishAnnotationName());
            }
        });
    }
    // Always attach a listener that logs write errors.
    writeFuture.addListener(logOnWriteErrorOperationListener(ctx));
    // Any other situation should be a close-only-on-failure.
    if (isLastChunk && (!requestInfo.isKeepAliveRequested() || responseInfo.isForceConnectionCloseAfterResponseSent())) {
        writeFuture.addListener(ChannelFutureListener.CLOSE);
    } else
        writeFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) Span(com.nike.wingtips.Span) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent)

Aggregations

LastHttpContent (io.netty.handler.codec.http.LastHttpContent)137 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)63 HttpContent (io.netty.handler.codec.http.HttpContent)55 ByteBuf (io.netty.buffer.ByteBuf)49 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)43 HttpResponse (io.netty.handler.codec.http.HttpResponse)42 HttpRequest (io.netty.handler.codec.http.HttpRequest)34 Test (org.junit.Test)27 Test (org.junit.jupiter.api.Test)24 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)23 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)20 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)13 IOException (java.io.IOException)12 ChannelFuture (io.netty.channel.ChannelFuture)11 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)10 HttpObject (io.netty.handler.codec.http.HttpObject)10 JsonObjectDecoder (io.netty.handler.codec.json.JsonObjectDecoder)10 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)9 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)9