Search in sources :

Example 1 with OK

use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.

the class HttpClientAsyncContextTest method makeClientRequestWithId.

private static void makeClientRequestWithId(StreamingHttpClient client, String requestId) throws ExecutionException, InterruptedException {
    StreamingHttpRequest request = client.get("/");
    request.headers().set(REQUEST_ID_HEADER, requestId);
    client.request(request).whenOnSuccess(response -> assertEquals(OK, response.status())).flatMapCompletable(response -> response.messageBody().ignoreElements()).toFuture().get();
}
Also used : FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) CharSequences.newAsciiString(io.servicetalk.buffer.api.CharSequences.newAsciiString) Key.newKey(io.servicetalk.context.api.ContextMap.Key.newKey) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) AsyncContext(io.servicetalk.concurrent.api.AsyncContext) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) HttpExecutionStrategies(io.servicetalk.http.api.HttpExecutionStrategies) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ValueSource(org.junit.jupiter.params.provider.ValueSource) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) Matchers.empty(org.hamcrest.Matchers.empty) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ExecutionException(java.util.concurrent.ExecutionException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ContextMap(io.servicetalk.context.api.ContextMap) Queue(java.util.Queue) HostAndPort(io.servicetalk.transport.api.HostAndPort) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest)

Example 2 with OK

use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.

the class HttpAuthConnectionFactoryClientTest method simulateAuth.

@Test
void simulateAuth() throws Exception {
    serverContext = forAddress(localAddress(0)).ioExecutor(CTX.ioExecutor()).executionStrategy(offloadNever()).listenStreamingAndAwait((ctx, request, factory) -> succeeded(newTestResponse(factory)));
    client = forSingleAddress(serverHostAndPort(serverContext)).appendConnectionFactoryFilter(TestHttpAuthConnectionFactory::new).ioExecutor(CTX.ioExecutor()).executionStrategy(offloadNever()).buildStreaming();
    StreamingHttpResponse response = client.request(newTestRequest(client, "/foo")).toFuture().get();
    assertEquals(OK, response.status());
}
Also used : StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) HttpServers.forAddress(io.servicetalk.http.netty.HttpServers.forAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) ZERO(io.servicetalk.http.api.HttpHeaderValues.ZERO) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Nullable(javax.annotation.Nullable) StreamingHttpRequestFactory(io.servicetalk.http.api.StreamingHttpRequestFactory) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) HttpClients.forSingleAddress(io.servicetalk.http.netty.HttpClients.forSingleAddress) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) TransportObserver(io.servicetalk.transport.api.TransportObserver) Single.failed(io.servicetalk.concurrent.api.Single.failed) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 3 with OK

use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.

the class ConnectionAcceptingNettyHttpServerTest method assertConnectionRequestSucceeds.

private void assertConnectionRequestSucceeds(final StreamingHttpRequest request) throws Exception {
    final StreamingHttpResponse response = awaitIndefinitely(streamingHttpClient().reserveConnection(request).flatMap(conn -> conn.request(request)));
    assert response != null;
    assertResponse(response, HTTP_1_1, OK, "");
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TRACE(io.servicetalk.logging.api.LogLevel.TRACE) TimeoutException(java.util.concurrent.TimeoutException) PlatformDependent.normalizedOs(io.netty.util.internal.PlatformDependent.normalizedOs) BlockingTestUtils.awaitIndefinitely(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitely) BlockingTestUtils.await(io.servicetalk.concurrent.api.BlockingTestUtils.await) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) SO_BACKLOG(io.servicetalk.transport.api.ServiceTalkSocketOptions.SO_BACKLOG) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Single(io.servicetalk.concurrent.api.Single) SVC_ECHO(io.servicetalk.http.netty.TestServiceStreaming.SVC_ECHO) CONNECT_TIMEOUT(io.servicetalk.transport.api.ServiceTalkSocketOptions.CONNECT_TIMEOUT) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) GET(io.servicetalk.http.api.HttpRequestMethod.GET) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) Test(org.junit.jupiter.api.Test) ExecutionException(java.util.concurrent.ExecutionException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) RetryingHttpRequesterFilter.disableAutoRetries(io.servicetalk.http.netty.RetryingHttpRequesterFilter.disableAutoRetries) LimitingConnectionFactoryFilter.withMax(io.servicetalk.client.api.LimitingConnectionFactoryFilter.withMax) ConnectTimeoutException(io.servicetalk.client.api.ConnectTimeoutException) TRUE(java.lang.Boolean.TRUE) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) SECONDS(java.util.concurrent.TimeUnit.SECONDS) HostAndPort(io.servicetalk.transport.api.HostAndPort) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse)

Example 4 with OK

use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.

the class HttpConnectionEmptyPayloadTest method headRequestContentEmpty.

@Test
void headRequestContentEmpty() throws Exception {
    try (CompositeCloseable closeable = AsyncCloseables.newCompositeCloseable()) {
        final int expectedContentLength = 128;
        byte[] expectedPayload = new byte[expectedContentLength];
        ThreadLocalRandom.current().nextBytes(expectedPayload);
        ServerContext serverContext = closeable.merge(HttpServers.forAddress(localAddress(0)).ioExecutor(executionContextRule.ioExecutor()).executionStrategy(offloadNever()).listenStreamingAndAwait((ctx, req, factory) -> {
            StreamingHttpResponse resp = factory.ok().payloadBody(from(HEAD.equals(req.method()) ? EMPTY_BUFFER : ctx.executionContext().bufferAllocator().newBuffer(expectedContentLength).writeBytes(expectedPayload)));
            resp.addHeader(CONTENT_LENGTH, String.valueOf(expectedContentLength));
            return succeeded(resp);
        }));
        StreamingHttpClient client = closeable.merge(forResolvedAddress(serverHostAndPort(serverContext)).ioExecutor(executionContextRule.ioExecutor()).protocols(h1().maxPipelinedRequests(3).build()).executor(executionContextRule.executor()).executionStrategy(defaultStrategy()).buildStreaming());
        StreamingHttpConnection connection = closeable.merge(client.reserveConnection(client.get("/")).toFuture().get());
        // Request HEAD, GET, HEAD to verify that we can keep reading data despite a HEAD request providing a hint
        // about content-length (and not actually providing the content).
        Single<StreamingHttpResponse> response1Single = connection.request(connection.newRequest(HEAD, "/"));
        Single<StreamingHttpResponse> response2Single = connection.request(connection.get("/"));
        Single<StreamingHttpResponse> response3Single = connection.request(connection.newRequest(HEAD, "/"));
        StreamingHttpResponse response = awaitIndefinitelyNonNull(response1Single);
        assertEquals(OK, response.status());
        CharSequence contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        // Drain the current response content so we will be able to read the next response.
        response.messageBody().ignoreElements().toFuture().get();
        response = awaitIndefinitelyNonNull(response2Single);
        assertEquals(OK, response.status());
        contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        Buffer buffer = awaitIndefinitelyNonNull(response.payloadBody().collect(() -> connection.connectionContext().executionContext().bufferAllocator().newBuffer(), Buffer::writeBytes));
        byte[] actualBytes = new byte[buffer.readableBytes()];
        buffer.readBytes(actualBytes);
        assertArrayEquals(expectedPayload, actualBytes);
        response = awaitIndefinitelyNonNull(response3Single);
        assertEquals(OK, response.status());
        contentLength = response.headers().get(CONTENT_LENGTH);
        assertNotNull(contentLength);
        assertEquals(expectedContentLength, parseInt(contentLength.toString()));
        response.messageBody().ignoreElements().toFuture().get();
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) EMPTY_BUFFER(io.servicetalk.buffer.api.EmptyBuffer.EMPTY_BUFFER) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) HEAD(io.servicetalk.http.api.HttpRequestMethod.HEAD) Single.succeeded(io.servicetalk.concurrent.api.Single.succeeded) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BlockingTestUtils.awaitIndefinitelyNonNull(io.servicetalk.concurrent.api.BlockingTestUtils.awaitIndefinitelyNonNull) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ExecutionContextExtension.immediate(io.servicetalk.transport.netty.internal.ExecutionContextExtension.immediate) ServerContext(io.servicetalk.transport.api.ServerContext) HttpProtocolConfigs.h1(io.servicetalk.http.netty.HttpProtocolConfigs.h1) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) Single(io.servicetalk.concurrent.api.Single) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) ExecutionContextExtension(io.servicetalk.transport.netty.internal.ExecutionContextExtension) CONTENT_LENGTH(io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH) OK(io.servicetalk.http.api.HttpResponseStatus.OK) Integer.parseInt(java.lang.Integer.parseInt) HttpClients.forResolvedAddress(io.servicetalk.http.netty.HttpClients.forResolvedAddress) Test(org.junit.jupiter.api.Test) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) Buffer(io.servicetalk.buffer.api.Buffer) AsyncCloseables(io.servicetalk.concurrent.api.AsyncCloseables) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) Buffer(io.servicetalk.buffer.api.Buffer) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ServerContext(io.servicetalk.transport.api.ServerContext) CompositeCloseable(io.servicetalk.concurrent.api.CompositeCloseable) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Test(org.junit.jupiter.api.Test)

Example 5 with OK

use of io.servicetalk.http.api.HttpResponseStatus.OK in project servicetalk by apple.

the class BlockingStreamingToStreamingServiceTest method throwAfterSendMetaData.

@Test
void throwAfterSendMetaData() throws Exception {
    CountDownLatch onErrorLatch = new CountDownLatch(1);
    AtomicReference<Throwable> throwableRef = new AtomicReference<>();
    BlockingStreamingHttpService syncService = (ctx, request, response) -> {
        response.sendMetaData();
        throw DELIBERATE_EXCEPTION;
    };
    StreamingHttpService asyncService = toStreamingHttpService(syncService, offloadNone()).adaptor();
    StreamingHttpResponse asyncResponse = asyncService.handle(mockCtx, reqRespFactory.get("/"), reqRespFactory).subscribeOn(executorExtension.executor()).toFuture().get();
    assertMetaData(OK, asyncResponse);
    toSource(asyncResponse.payloadBody()).subscribe(new Subscriber<Buffer>() {

        @Override
        public void onSubscribe(final Subscription s) {
        }

        @Override
        public void onNext(final Buffer s) {
        }

        @Override
        public void onError(final Throwable t) {
            throwableRef.set(t);
            onErrorLatch.countDown();
        }

        @Override
        public void onComplete() {
        }
    });
    onErrorLatch.await();
    assertThat(throwableRef.get(), is(DELIBERATE_EXCEPTION));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) PlatformDependent.throwException(io.servicetalk.utils.internal.PlatformDependent.throwException) BiFunction(java.util.function.BiFunction) SingleSource(io.servicetalk.concurrent.SingleSource) ServiceAdapterHolder(io.servicetalk.http.api.HttpApiConversions.ServiceAdapterHolder) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Executor(io.servicetalk.concurrent.api.Executor) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ExecutorExtension(io.servicetalk.concurrent.api.ExecutorExtension) PayloadWriter(io.servicetalk.oio.api.PayloadWriter) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) Function.identity(java.util.function.Function.identity) Matchers.is(org.hamcrest.Matchers.is) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) Publisher(io.servicetalk.concurrent.api.Publisher) Mock(org.mockito.Mock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cancellable(io.servicetalk.concurrent.Cancellable) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Mockito.lenient(org.mockito.Mockito.lenient) Subscriber(io.servicetalk.concurrent.PublisherSource.Subscriber) ArrayList(java.util.ArrayList) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) HttpSerializers.appSerializerUtf8FixLen(io.servicetalk.http.api.HttpSerializers.appSerializerUtf8FixLen) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Publisher.from(io.servicetalk.concurrent.api.Publisher.from) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) Nullable(javax.annotation.Nullable) TRAILER(io.servicetalk.http.api.HttpHeaderNames.TRAILER) UTF_8(java.nio.charset.StandardCharsets.UTF_8) NO_CONTENT(io.servicetalk.http.api.HttpResponseStatus.NO_CONTENT) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) OK(io.servicetalk.http.api.HttpResponseStatus.OK) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) ExecutionException(java.util.concurrent.ExecutionException) Publisher.failed(io.servicetalk.concurrent.api.Publisher.failed) HTTP_1_1(io.servicetalk.http.api.HttpProtocolVersion.HTTP_1_1) InputStream(java.io.InputStream) Buffer(io.servicetalk.buffer.api.Buffer) HttpApiConversions.toStreamingHttpService(io.servicetalk.http.api.HttpApiConversions.toStreamingHttpService) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) Test(org.junit.jupiter.api.Test)

Aggregations

OK (io.servicetalk.http.api.HttpResponseStatus.OK)17 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)13 Single.succeeded (io.servicetalk.concurrent.api.Single.succeeded)9 HttpResponse (io.servicetalk.http.api.HttpResponse)9 Single (io.servicetalk.concurrent.api.Single)8 ServerContext (io.servicetalk.transport.api.ServerContext)8 AddressUtils.localAddress (io.servicetalk.transport.netty.internal.AddressUtils.localAddress)8 Test (org.junit.jupiter.api.Test)8 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)7 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)6 AddressUtils.serverHostAndPort (io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort)6 Buffer (io.servicetalk.buffer.api.Buffer)5 Publisher.from (io.servicetalk.concurrent.api.Publisher.from)5 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)5 HOST (io.servicetalk.http.api.HttpHeaderNames.HOST)5 HttpRequest (io.servicetalk.http.api.HttpRequest)5 Matchers.is (org.hamcrest.Matchers.is)5 Publisher (io.servicetalk.concurrent.api.Publisher)4 AbstractHttpRequesterFilterTest (io.servicetalk.http.api.AbstractHttpRequesterFilterTest)4 BlockingHttpRequester (io.servicetalk.http.api.BlockingHttpRequester)4