Search in sources :

Example 1 with HttpClient

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

the class ClientEffectiveStrategyTest method getResponse.

private String getResponse(ClientType clientType, StreamingHttpClient client) throws Exception {
    switch(clientType) {
        case Blocking:
            BlockingHttpClient blockingClient = client.asBlockingClient();
            return blockingClient.request(blockingClient.get("/")).payloadBody().toString(StandardCharsets.US_ASCII);
        case BlockingStreaming:
            BlockingStreamingHttpClient blockingStreamingClient = client.asBlockingStreamingClient();
            Supplier<CompositeBuffer> supplier = client.executionContext().bufferAllocator()::newCompositeBuffer;
            return StreamSupport.stream(blockingStreamingClient.request(blockingStreamingClient.get("/")).payloadBody().spliterator(), false).reduce((Buffer base, Buffer buffer) -> (base instanceof CompositeBuffer ? ((CompositeBuffer) base) : supplier.get().addBuffer(base)).addBuffer(buffer)).map(buffer -> buffer.toString(StandardCharsets.US_ASCII)).orElse("");
        case AsyncStreaming:
            return client.request(client.get("/")).flatMap(resp -> resp.payloadBody().collect(() -> client.executionContext().bufferAllocator().newCompositeBuffer(), CompositeBuffer::addBuffer)).toFuture().get().toString(StandardCharsets.US_ASCII);
        case Async:
            HttpClient httpClient = client.asClient();
            return httpClient.request(httpClient.get("/")).toFuture().get().payloadBody().toString(StandardCharsets.US_ASCII);
        default:
            fail("Unexpected client type " + clientType);
            /* NOTREACHED */
            return "failed";
    }
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) ResponseData(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.ResponseData) StreamingHttpConnectionFilterFactory(io.servicetalk.http.api.StreamingHttpConnectionFilterFactory) LoadBalancer(io.servicetalk.client.api.LoadBalancer) ServiceDiscovererEvent(io.servicetalk.client.api.ServiceDiscovererEvent) AfterAll(org.junit.jupiter.api.AfterAll) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) HttpExecutionStrategies.offloadNone(io.servicetalk.http.api.HttpExecutionStrategies.offloadNone) EnumSet(java.util.EnumSet) MethodSource(org.junit.jupiter.params.provider.MethodSource) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) ExecutionMode(org.junit.jupiter.api.parallel.ExecutionMode) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StreamingHttpClientFilter(io.servicetalk.http.api.StreamingHttpClientFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) InetSocketAddress(java.net.InetSocketAddress) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) FilterableStreamingHttpLoadBalancedConnection(io.servicetalk.http.api.FilterableStreamingHttpLoadBalancedConnection) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) Stream(java.util.stream.Stream) HttpExecutionStrategies.offloadAll(io.servicetalk.http.api.HttpExecutionStrategies.offloadAll) ResponseMeta(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.ResponseMeta) RoundRobinLoadBalancerFactory(io.servicetalk.loadbalancer.RoundRobinLoadBalancerFactory) Queue(java.util.Queue) Assertions.fail(org.junit.jupiter.api.Assertions.fail) RequestPayloadSubscription(io.servicetalk.http.netty.ClientEffectiveStrategyTest.ClientOffloadPoint.RequestPayloadSubscription) LoadBalancerFactory(io.servicetalk.client.api.LoadBalancerFactory) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Publisher(io.servicetalk.concurrent.api.Publisher) StreamingHttpRequester(io.servicetalk.http.api.StreamingHttpRequester) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) HttpLoadBalancerFactory(io.servicetalk.http.api.HttpLoadBalancerFactory) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) IoThreadFactory(io.servicetalk.transport.api.IoThreadFactory) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) HttpExecutionStrategies(io.servicetalk.http.api.HttpExecutionStrategies) HttpExecutionStrategy(io.servicetalk.http.api.HttpExecutionStrategy) HttpClient(io.servicetalk.http.api.HttpClient) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) StreamSupport(java.util.stream.StreamSupport) AddressUtils.serverHostAndPort(io.servicetalk.transport.netty.internal.AddressUtils.serverHostAndPort) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) HttpServerBuilder(io.servicetalk.http.api.HttpServerBuilder) Nullable(javax.annotation.Nullable) ConnectionFactory(io.servicetalk.client.api.ConnectionFactory) AddressUtils.localAddress(io.servicetalk.transport.netty.internal.AddressUtils.localAddress) ServerContext(io.servicetalk.transport.api.ServerContext) Single(io.servicetalk.concurrent.api.Single) Matchers(org.hamcrest.Matchers) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) StreamingHttpClientFilterFactory(io.servicetalk.http.api.StreamingHttpClientFilterFactory) Execution(org.junit.jupiter.api.parallel.Execution) HostAndPort(io.servicetalk.transport.api.HostAndPort) HttpExecutionStrategies.offloadNever(io.servicetalk.http.api.HttpExecutionStrategies.offloadNever) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) CompositeBuffer(io.servicetalk.buffer.api.CompositeBuffer) FilterableStreamingHttpClient(io.servicetalk.http.api.FilterableStreamingHttpClient) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) BlockingHttpClient(io.servicetalk.http.api.BlockingHttpClient) HttpClient(io.servicetalk.http.api.HttpClient) BlockingStreamingHttpClient(io.servicetalk.http.api.BlockingStreamingHttpClient)

Example 2 with HttpClient

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

the class MultiAddressUrlRedirectClient method main.

public static void main(String... args) throws Exception {
    try (HttpClient client = HttpClients.forMultiAddressUrl().followRedirects(new RedirectConfigBuilder().maxRedirects(3).allowNonRelativeRedirects(true).allowedMethods(GET, POST).redirectPredicate((relative, redirectCount, prevRequest, redirectResponse) -> // allow only relative redirects
    relative || // OR non-relative redirects to a trusted server:
    redirectResponse.headers().get(LOCATION, "").toString().startsWith("https://localhost:" + SECURE_SERVER_PORT)).headersToRedirect(CUSTOM_HEADER).redirectPayloadBody(true).redirectRequestTransformer((relative, prevRequest, redirectResponse, redirectedRequest) -> {
        // prevRequest and redirectResponse: check/copy other headers, modify request method, etc.
        return redirectedRequest;
    }).build()).initializer((scheme, address, builder) -> {
        // already provides default SSL configuration and this step may be skipped.
        if ("https".equalsIgnoreCase(scheme)) {
            builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build());
        }
    }).build()) {
        final String serverThatRedirects = "http://localhost:" + NON_SECURE_SERVER_PORT;
        System.out.println("- Simple GET request:");
        client.request(client.get(serverThatRedirects + "/relative")).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
        System.out.println("- Non-relative redirect for POST request with headers and payload body:");
        client.request(client.post(serverThatRedirects + "/non-relative").addHeader(CUSTOM_HEADER, "value").payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerAscii()));
            System.out.println();
        }).toFuture().get();
    }
}
Also used : HttpSerializers.textSerializerAscii(io.servicetalk.http.api.HttpSerializers.textSerializerAscii) HttpRequestMethod(io.servicetalk.http.api.HttpRequestMethod) CUSTOM_HEADER(io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER) LOCATION(io.servicetalk.http.api.HttpHeaderNames.LOCATION) POST(io.servicetalk.http.api.HttpRequestMethod.POST) MultiAddressHttpClientBuilder(io.servicetalk.http.api.MultiAddressHttpClientBuilder) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) GET(io.servicetalk.http.api.HttpRequestMethod.GET) SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.SECURE_SERVER_PORT) NON_SECURE_SERVER_PORT(io.servicetalk.examples.http.redirects.RedirectingServer.NON_SECURE_SERVER_PORT) RedirectConfig(io.servicetalk.http.api.RedirectConfig) HttpClient(io.servicetalk.http.api.HttpClient) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder) DefaultTestCerts(io.servicetalk.test.resources.DefaultTestCerts) HttpClients(io.servicetalk.http.netty.HttpClients) HttpClient(io.servicetalk.http.api.HttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) ClientSslConfigBuilder(io.servicetalk.transport.api.ClientSslConfigBuilder)

Example 3 with HttpClient

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

the class RetryUrlClient method main.

public static void main(String[] args) throws Exception {
    try (HttpClient client = HttpClients.forMultiAddressUrl().initializer((scheme, address, builder) -> {
        builder.appendClientFilter(new RetryingHttpRequesterFilter.Builder().responseMapper(httpResponseMetaData -> SERVER_ERROR_5XX.contains(httpResponseMetaData.status()) ? // Response status is 500-599, we request a retry
        new RetryingHttpRequesterFilter.HttpResponseException("Retry 5XX", httpResponseMetaData) : // Not a 5XX response, we do not know whether retry is required
        null).retryResponses((meta, error) -> RetryingHttpRequesterFilter.BackOffPolicy.ofImmediate(2)).build());
    }).build()) {
        client.request(client.get("http://localhost:8080/sayHello")).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(textSerializerUtf8()));
        }).toFuture().get();
    }
}
Also used : RetryingHttpRequesterFilter(io.servicetalk.http.netty.RetryingHttpRequesterFilter) HttpSerializers.textSerializerUtf8(io.servicetalk.http.api.HttpSerializers.textSerializerUtf8) HttpClient(io.servicetalk.http.api.HttpClient) HttpClients(io.servicetalk.http.netty.HttpClients) SERVER_ERROR_5XX(io.servicetalk.http.api.HttpResponseStatus.StatusClass.SERVER_ERROR_5XX) HttpClient(io.servicetalk.http.api.HttpClient) RetryingHttpRequesterFilter(io.servicetalk.http.netty.RetryingHttpRequesterFilter)

Example 4 with HttpClient

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

the class PojoClient method main.

public static void main(String[] args) throws Exception {
    try (HttpClient client = HttpClients.forSingleAddress("localhost", 8080).build()) {
        client.request(client.post("/pojos").payloadBody(new CreatePojoRequest("value"), REQ_SERIALIZER)).whenOnSuccess(resp -> {
            System.out.println(resp.toString((name, value) -> value));
            System.out.println(resp.payloadBody(RESP_SERIALIZER));
        }).toFuture().get();
    }
}
Also used : CreatePojoRequest(io.servicetalk.examples.http.serialization.json.CreatePojoRequest) REQ_SERIALIZER(io.servicetalk.examples.http.serialization.json.SerializerUtils.REQ_SERIALIZER) HttpClient(io.servicetalk.http.api.HttpClient) RESP_SERIALIZER(io.servicetalk.examples.http.serialization.json.SerializerUtils.RESP_SERIALIZER) HttpClients(io.servicetalk.http.netty.HttpClients) CreatePojoRequest(io.servicetalk.examples.http.serialization.json.CreatePojoRequest) HttpClient(io.servicetalk.http.api.HttpClient)

Example 5 with HttpClient

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

the class ExpectContinueTest method retryExpectationFailedAggregated.

@ParameterizedTest(name = "protocol={0} withCL={1}")
@MethodSource("arguments")
void retryExpectationFailedAggregated(HttpProtocol protocol, boolean withCL) throws Exception {
    try (HttpServerContext serverContext = startServer(protocol);
        HttpClient client = createClient(serverContext, protocol, new RetryingHttpRequesterFilter.Builder().retryExpectationFailed(true).build()).asClient()) {
        Future<HttpResponse> responseFuture = client.request(newRequest(client, withCL, true, PAYLOAD + PAYLOAD, client.executionContext().bufferAllocator())).toFuture();
        requestReceived.await();
        sendContinue.countDown();
        returnResponse.countDown();
        HttpResponse response = responseFuture.get();
        assertThat(response.status(), is(OK));
        assertThat(response.payloadBody().toString(US_ASCII), equalTo(PAYLOAD + PAYLOAD));
    }
}
Also used : StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) HttpClient(io.servicetalk.http.api.HttpClient) RedirectConfigBuilder(io.servicetalk.http.api.RedirectConfigBuilder) SingleAddressHttpClientBuilder(io.servicetalk.http.api.SingleAddressHttpClientBuilder) HttpServerContext(io.servicetalk.http.api.HttpServerContext) HttpResponse(io.servicetalk.http.api.HttpResponse) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

HttpClient (io.servicetalk.http.api.HttpClient)34 HttpResponse (io.servicetalk.http.api.HttpResponse)14 HttpClients (io.servicetalk.http.netty.HttpClients)14 ServerContext (io.servicetalk.transport.api.ServerContext)12 Test (org.junit.jupiter.api.Test)11 HttpRequest (io.servicetalk.http.api.HttpRequest)10 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)9 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)9 HttpSerializers.textSerializerUtf8 (io.servicetalk.http.api.HttpSerializers.textSerializerUtf8)8 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)7 Single (io.servicetalk.concurrent.api.Single)6 SingleAddressHttpClientBuilder (io.servicetalk.http.api.SingleAddressHttpClientBuilder)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 BlockingHttpClient (io.servicetalk.http.api.BlockingHttpClient)5 BlockingStreamingHttpClient (io.servicetalk.http.api.BlockingStreamingHttpClient)5 CountingInMemorySpanEventListener (io.servicetalk.opentracing.http.TestUtils.CountingInMemorySpanEventListener)5 Completable (io.servicetalk.concurrent.api.Completable)4 Publisher (io.servicetalk.concurrent.api.Publisher)4 FilterableStreamingHttpClient (io.servicetalk.http.api.FilterableStreamingHttpClient)4 List (java.util.List)4