Search in sources :

Example 21 with HttpHeaders

use of io.servicetalk.http.api.HttpHeaders in project servicetalk by apple.

the class ContentLengthAndTrailersTest method setUp.

private void setUp(HttpProtocol protocol, String content) {
    this.protocol = protocol;
    this.content = content;
    protocol(protocol.config);
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            // Use transform to simulate access to request trailers
            return delegate().handle(ctx, request.transform(new StatelessTrailersTransformer<>()), responseFactory).map(response -> {
                final HttpHeaders headers = request.headers();
                if (headers.contains(CONTENT_LENGTH)) {
                    response.setHeader(CLIENT_CONTENT_LENGTH, mergeValues(headers.values(CONTENT_LENGTH)));
                }
                if (headers.contains(TRANSFER_ENCODING)) {
                    response.setHeader(CLIENT_TRANSFER_ENCODING, mergeValues(headers.values(TRANSFER_ENCODING)));
                }
                return response;
            });
        }
    });
    setUp(CACHED, CACHED_SERVER);
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) CONTENT_TYPE(io.servicetalk.http.api.HttpHeaderNames.CONTENT_TYPE) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) ArrayList(java.util.ArrayList) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpMetaData(io.servicetalk.http.api.HttpMetaData) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.contentEqualTo(io.servicetalk.buffer.api.Matchers.contentEqualTo) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) Nullable(javax.annotation.Nullable) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) MethodSource(org.junit.jupiter.params.provider.MethodSource) Single(io.servicetalk.concurrent.api.Single) TRANSFER_ENCODING(io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) Arguments(org.junit.jupiter.params.provider.Arguments) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) String.valueOf(java.lang.String.valueOf) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) Matchers.equalTo(org.hamcrest.Matchers.equalTo) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) HTTP_1(io.servicetalk.http.netty.HttpProtocol.HTTP_1) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StatelessTrailersTransformer(io.servicetalk.http.api.StatelessTrailersTransformer) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest)

Example 22 with HttpHeaders

use of io.servicetalk.http.api.HttpHeaders in project servicetalk by apple.

the class ConsumeRequestPayloadOnResponsePathTest method test.

private void test(final BiFunction<Single<StreamingHttpResponse>, StreamingHttpRequest, Single<StreamingHttpResponse>> consumeRequestPayload) throws Exception {
    try (ServerContext serverContext = HttpServers.forAddress(localAddress(0)).appendServiceFilter(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(final HttpServiceContext ctx, final StreamingHttpRequest request, final StreamingHttpResponseFactory responseFactory) {
            return consumeRequestPayload.apply(delegate().handle(ctx, request, responseFactory), request);
        }
    }).listenStreamingAndAwait((ctx, request, responseFactory) -> {
        final StreamingHttpResponse response = responseFactory.ok().addHeader(TRAILER, X_TOTAL_LENGTH).payloadBody(from("Response\n", "Payload\n", "Body\n"), appSerializerUtf8FixLen()).transform(new TrailersTransformer<AtomicInteger, Buffer>() {

            @Override
            public AtomicInteger newState() {
                return new AtomicInteger();
            }

            @Override
            public Buffer accept(final AtomicInteger total, final Buffer chunk) {
                total.addAndGet(chunk.readableBytes());
                return chunk;
            }

            @Override
            public HttpHeaders payloadComplete(final AtomicInteger total, final HttpHeaders trailers) {
                trailers.add(X_TOTAL_LENGTH, String.valueOf(total.get()));
                return trailers;
            }

            @Override
            public HttpHeaders catchPayloadFailure(final AtomicInteger __, final Throwable ___, final HttpHeaders trailers) {
                return trailers;
            }
        });
        return succeeded(response);
    })) {
        HttpResponse response;
        try (BlockingHttpClient client = HttpClients.forSingleAddress(AddressUtils.serverHostAndPort(serverContext)).buildBlocking()) {
            response = client.request(client.post("/").payloadBody(EXPECTED_REQUEST_PAYLOAD, textSerializerUtf8()));
            serverLatch.await();
        }
        assertThat(response.status(), is(OK));
        assertThat("Request payload body might be consumed by someone else", errorRef.get(), is(nullValue()));
        assertThat(receivedPayload.toString(), is(EXPECTED_REQUEST_PAYLOAD));
        assertThat(response.headers().contains(TRAILER, X_TOTAL_LENGTH), is(true));
        assertThat(response.trailers().contains(X_TOTAL_LENGTH), is(true));
        CharSequence trailerLength = response.trailers().get(X_TOTAL_LENGTH);
        assertNotNull(trailerLength);
        assertThat("Unexpected response payload: '" + response.payloadBody().toString(UTF_8) + "'", trailerLength.toString(), is(Integer.toString(response.payloadBody().readableBytes())));
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) TrailersTransformer(io.servicetalk.http.api.TrailersTransformer) BiFunction(java.util.function.BiFunction) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpResponses.newTransportResponse(io.servicetalk.http.api.StreamingHttpResponses.newTransportResponse) PlatformDependent(io.servicetalk.utils.internal.PlatformDependent) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) Matchers.nullValue(org.hamcrest.Matchers.nullValue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) TRAILER(io.servicetalk.http.api.HttpHeaderNames.TRAILER) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) HttpResponse(io.servicetalk.http.api.HttpResponse) OK(io.servicetalk.http.api.HttpResponseStatus.OK) DefaultHttpHeadersFactory(io.servicetalk.http.api.DefaultHttpHeadersFactory) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Matchers.is(org.hamcrest.Matchers.is) AddressUtils(io.servicetalk.transport.netty.internal.AddressUtils) Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) ServerContext(io.servicetalk.transport.api.ServerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 23 with HttpHeaders

use of io.servicetalk.http.api.HttpHeaders in project servicetalk by apple.

the class BlockingStreamingHttpServiceTest method respondWithPayloadBodyAndTrailers.

private void respondWithPayloadBodyAndTrailers(BlockingStreamingHttpService handler, boolean useDeserializer) throws Exception {
    BlockingStreamingHttpClient client = context(handler);
    BlockingStreamingHttpResponse response = client.request(client.get("/"));
    assertResponse(response);
    assertThat(response.headers().get(TRAILER).toString(), is(X_TOTAL_LENGTH));
    final StringBuilder sb = new StringBuilder();
    final HttpHeaders trailers;
    if (useDeserializer) {
        HttpMessageBodyIterator<String> msgBody = response.messageBody(appSerializerUtf8FixLen()).iterator();
        while (msgBody.hasNext()) {
            sb.append(msgBody.next());
        }
        trailers = msgBody.trailers();
    } else {
        HttpMessageBodyIterator<Buffer> msgBody = response.messageBody().iterator();
        while (msgBody.hasNext()) {
            sb.append(requireNonNull(msgBody.next()).toString(UTF_8));
        }
        trailers = msgBody.trailers();
    }
    assertThat(sb.toString(), is(HELLO_WORLD));
    assertThat(trailers, notNullValue());
    assertThat(trailers.get(X_TOTAL_LENGTH).toString(), is(HELLO_WORLD_LENGTH));
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse)

Example 24 with HttpHeaders

use of io.servicetalk.http.api.HttpHeaders in project servicetalk by apple.

the class BlockingStreamingHttpServiceTest method setRequestMessageBody.

@Test
void setRequestMessageBody() throws Exception {
    BlockingStreamingHttpClient client = context((ctx, request, response) -> {
        response.status(OK);
        try {
            HttpMessageBodyIterator<Buffer> reqItr = request.messageBody().iterator();
            StringBuilder sb = new StringBuilder();
            while (reqItr.hasNext()) {
                sb.append(requireNonNull(reqItr.next()).toString(UTF_8));
            }
            assertThat(sb.toString(), is(HELLO_WORLD));
            HttpHeaders trailers = reqItr.trailers();
            assertThat(trailers, notNullValue());
            assertThat(trailers.get(X_TOTAL_LENGTH).toString(), is(HELLO_WORLD_LENGTH));
        } catch (Throwable cause) {
            HttpPayloadWriter<String> payloadWriter = response.sendMetaData(appSerializerUtf8FixLen());
            payloadWriter.write(cause.toString());
            payloadWriter.close();
            return;
        }
        response.sendMetaData(appSerializerUtf8FixLen()).close();
    });
    BufferAllocator alloc = client.executionContext().bufferAllocator();
    BlockingStreamingHttpRequest req = client.get("/");
    req.setHeader(TRAILER, X_TOTAL_LENGTH);
    int split = HELLO_WORLD.length() / 2;
    final BlockingIterable<Buffer> reqIterable = BlockingIterables.from(asList(alloc.fromAscii(HELLO_WORLD.substring(0, split)), alloc.fromAscii(HELLO_WORLD.substring(split))));
    req.messageBody(() -> new HttpMessageBodyIterator<Buffer>() {

        private final BlockingIterator<Buffer> iterator = reqIterable.iterator();

        @Nullable
        private HttpHeaders trailers;

        private int totalLength;

        @Nullable
        @Override
        public HttpHeaders trailers() {
            if (trailers == null) {
                trailers = DefaultHttpHeadersFactory.INSTANCE.newTrailers();
                trailers.set(X_TOTAL_LENGTH, String.valueOf(totalLength));
            }
            return trailers;
        }

        @Override
        public boolean hasNext(final long timeout, final TimeUnit unit) throws TimeoutException {
            return iterator.hasNext(timeout, unit);
        }

        @Nullable
        @Override
        public Buffer next(final long timeout, final TimeUnit unit) throws TimeoutException {
            return addTotalLength(iterator.next(timeout, unit));
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Nullable
        @Override
        public Buffer next() {
            return addTotalLength(iterator.next());
        }

        @Override
        public void close() throws Exception {
            iterator.close();
        }

        @Nullable
        private Buffer addTotalLength(@Nullable Buffer buffer) {
            if (buffer != null) {
                totalLength += buffer.readableBytes();
            }
            return buffer;
        }
    });
    BlockingStreamingHttpResponse response = client.request(req);
    assertThat(response.status(), is(OK));
    assertThat(stream(response.payloadBody(appSerializerUtf8FixLen()).spliterator(), false).collect(Collectors.toList()), emptyIterable());
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingStreamingHttpRequest(io.servicetalk.http.api.BlockingStreamingHttpRequest) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BufferAllocator(io.servicetalk.buffer.api.BufferAllocator) BlockingStreamingHttpResponse(io.servicetalk.http.api.BlockingStreamingHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpPayloadWriter(io.servicetalk.http.api.HttpPayloadWriter) Nullable(javax.annotation.Nullable) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 25 with HttpHeaders

use of io.servicetalk.http.api.HttpHeaders in project servicetalk by apple.

the class AbstractEchoServerBasedHttpRequesterTest method makeRequestValidateResponseAndClose.

static void makeRequestValidateResponseAndClose(StreamingHttpRequester requester) throws ExecutionException, InterruptedException {
    try {
        StreamingHttpRequest request = requester.get("/request?foo=bar&foo=baz").payloadBody(from(DEFAULT_ALLOCATOR.fromAscii("Testing123")));
        request.headers().set(HOST, "mock.servicetalk.io");
        StreamingHttpResponse resp = awaitIndefinitelyNonNull(requester.request(request).retryWhen(retryWithExponentialBackoffFullJitter(10, t -> true, ofMillis(100), ofDays(10), CTX.executor())));
        assertThat(resp.status(), equalTo(OK));
        Single<String> respBody = resp.payloadBody().collect(StringBuilder::new, (sb, buf) -> {
            sb.append(buf.toString(UTF_8));
            return sb;
        }).map(StringBuilder::toString);
        HttpHeaders headers = resp.headers();
        assertThat(headers.get("test-req-method"), hasToString(GET.toString()));
        assertThat(headers.get("test-req-target"), hasToString("/request?foo=bar&foo=baz"));
        assertThat(headers.get("test-req-header-host"), hasToString("mock.servicetalk.io"));
        assertThat(headers.get("test-req-header-transfer-encoding"), equalTo(CHUNKED));
        assertThat(respBody.toFuture().get(), equalTo("Testing123"));
    } finally {
        requester.closeAsync().toFuture().get();
    }
}
Also used : Matchers.hasToString(org.hamcrest.Matchers.hasToString) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) IsEqual.equalTo(org.hamcrest.core.IsEqual.equalTo) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) AfterAll(org.junit.jupiter.api.AfterAll) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) TestInstance(org.junit.jupiter.api.TestInstance) BeforeAll(org.junit.jupiter.api.BeforeAll) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HOST(io.servicetalk.http.api.HttpHeaderNames.HOST) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) CHUNKED(io.servicetalk.http.api.HttpHeaderValues.CHUNKED) Duration.ofDays(java.time.Duration.ofDays) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) RetryStrategies.retryWithExponentialBackoffFullJitter(io.servicetalk.concurrent.api.RetryStrategies.retryWithExponentialBackoffFullJitter) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Single(io.servicetalk.concurrent.api.Single) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) OK(io.servicetalk.http.api.HttpResponseStatus.OK) GET(io.servicetalk.http.api.HttpRequestMethod.GET) ExecutionException(java.util.concurrent.ExecutionException) StreamingHttpService(io.servicetalk.http.api.StreamingHttpService) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) Duration.ofMillis(java.time.Duration.ofMillis) HttpHeaders(io.servicetalk.http.api.HttpHeaders) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) Matchers.hasToString(org.hamcrest.Matchers.hasToString) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Aggregations

HttpHeaders (io.servicetalk.http.api.HttpHeaders)43 Buffer (io.servicetalk.buffer.api.Buffer)25 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)13 Test (org.junit.jupiter.api.Test)13 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)12 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 HttpMetaData (io.servicetalk.http.api.HttpMetaData)11 Nullable (javax.annotation.Nullable)11 Http2Headers (io.netty.handler.codec.http2.Http2Headers)10 Single (io.servicetalk.concurrent.api.Single)9 StreamingHttpResponseFactory (io.servicetalk.http.api.StreamingHttpResponseFactory)9 Publisher (io.servicetalk.concurrent.api.Publisher)8 HttpResponseMetaData (io.servicetalk.http.api.HttpResponseMetaData)8 HttpServiceContext (io.servicetalk.http.api.HttpServiceContext)8 DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)7 EmptyHttpHeaders (io.servicetalk.http.api.EmptyHttpHeaders)7 CONTENT_LENGTH (io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH)7 CHUNKED (io.servicetalk.http.api.HttpHeaderValues.CHUNKED)7 DefaultHttp2DataFrame (io.netty.handler.codec.http2.DefaultHttp2DataFrame)5 HttpExecutionStrategy (io.servicetalk.http.api.HttpExecutionStrategy)5