Search in sources :

Example 1 with ReactiveResponseConsumer

use of org.apache.hc.core5.reactive.ReactiveResponseConsumer in project httpcomponents-core by apache.

the class ReactiveFullDuplexClientExample method main.

public static void main(final String[] args) throws Exception {
    String endpoint = "http://localhost:8080/echo";
    if (args.length >= 1) {
        endpoint = args[0];
    }
    // Create and start requester
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build()).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final Random random = new Random();
    final Flowable<ByteBuffer> publisher = Flowable.range(1, 100).map(ignored -> {
        final String str = random.nextDouble() + "\n";
        return ByteBuffer.wrap(str.getBytes(UTF_8));
    });
    final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(new URI(endpoint)).setEntity(new ReactiveEntityProducer(publisher, -1, ContentType.TEXT_PLAIN, null)).build();
    final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
    final Future<Void> responseComplete = requester.execute(requestProducer, consumer, Timeout.ofSeconds(30), null);
    final Message<HttpResponse, Publisher<ByteBuffer>> streamingResponse = consumer.getResponseFuture().get();
    System.out.println(streamingResponse.getHead());
    for (final Header header : streamingResponse.getHead().getHeaders()) {
        System.out.println(header);
    }
    System.out.println();
    Observable.fromPublisher(streamingResponse.getBody()).map(byteBuffer -> {
        final byte[] string = new byte[byteBuffer.remaining()];
        byteBuffer.get(string);
        return new String(string);
    }).materialize().forEach(System.out::println);
    responseComplete.get(1, TimeUnit.MINUTES);
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) Publisher(org.reactivestreams.Publisher) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) Timeout(org.apache.hc.core5.util.Timeout) StatusLine(org.apache.hc.core5.http.message.StatusLine) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) RequestLine(org.apache.hc.core5.http.message.RequestLine) Random(java.util.Random) Header(org.apache.hc.core5.http.Header) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 2 with ReactiveResponseConsumer

use of org.apache.hc.core5.reactive.ReactiveResponseConsumer in project httpcomponents-core by apache.

the class ReactiveClientTest method testRequestTimeout.

@Test
public void testRequestTimeout() throws Exception {
    final InetSocketAddress address = startClientAndServer();
    final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(false);
    final Publisher<ByteBuffer> publisher = Flowable.<ByteBuffer>never().doOnCancel(() -> requestPublisherWasCancelled.set(true));
    final ReactiveEntityProducer producer = new ReactiveEntityProducer(publisher, -1, null, null);
    final BasicRequestProducer request = getRequestProducer(address, producer);
    final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
    final Future<Void> future = requester.execute(request, consumer, Timeout.ofSeconds(1), null);
    final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, () -> future.get(RESULT_TIMEOUT.getDuration(), RESULT_TIMEOUT.getTimeUnit()));
    Assertions.assertTrue(requestPublisherWasCancelled.get());
    final Throwable cause = exception.getCause();
    if (versionPolicy == HttpVersionPolicy.FORCE_HTTP_1) {
        Assertions.assertTrue(cause instanceof SocketTimeoutException, "Expected SocketTimeoutException, but got " + cause.getClass().getName());
    } else if (versionPolicy == HttpVersionPolicy.FORCE_HTTP_2) {
        Assertions.assertTrue(cause instanceof HttpStreamResetException, format("Expected RST_STREAM, but %s was thrown", cause.getClass().getName()));
    } else {
        Assertions.fail("Unknown HttpVersionPolicy: " + versionPolicy);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) ByteBuffer(java.nio.ByteBuffer) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SocketTimeoutException(java.net.SocketTimeoutException) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) ExecutionException(java.util.concurrent.ExecutionException) HttpStreamResetException(org.apache.hc.core5.http.HttpStreamResetException) Test(org.junit.Test)

Example 3 with ReactiveResponseConsumer

use of org.apache.hc.core5.reactive.ReactiveResponseConsumer in project httpcomponents-core by apache.

the class ReactiveClientTest method testManySmallBuffers.

@Test
public void testManySmallBuffers() throws Exception {
    // This test is not flaky. If it starts randomly failing, then there is a problem with how
    // ReactiveDataConsumer signals capacity with its capacity channel. The situations in which
    // this kind of bug manifests depend on the ordering of several events on different threads
    // so it's unlikely to consistently occur.
    final InetSocketAddress address = startClientAndServer();
    for (int i = 0; i < 10; i++) {
        final long expectedLength = 1_024_000;
        final int maximumBlockSize = 1024;
        final AtomicReference<String> expectedHash = new AtomicReference<>();
        final Publisher<ByteBuffer> stream = ReactiveTestUtils.produceStream(expectedLength, maximumBlockSize, expectedHash);
        final ReactiveEntityProducer producer = new ReactiveEntityProducer(stream, -1, null, null);
        final BasicRequestProducer request = getRequestProducer(address, producer);
        final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
        requester.execute(request, consumer, SOCKET_TIMEOUT, null);
        final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get(RESULT_TIMEOUT.getDuration(), RESULT_TIMEOUT.getTimeUnit());
        final StreamDescription desc = ReactiveTestUtils.consumeStream(response.getBody()).blockingGet();
        Assertions.assertEquals(expectedLength, desc.length);
        Assertions.assertEquals(expectedHash.get(), TextUtils.toHexString(desc.md.digest()));
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(org.reactivestreams.Publisher) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) StreamDescription(org.apache.hc.core5.testing.reactive.ReactiveTestUtils.StreamDescription) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) Test(org.junit.Test)

Example 4 with ReactiveResponseConsumer

use of org.apache.hc.core5.reactive.ReactiveResponseConsumer in project spring-framework by spring-projects.

the class HttpComponentsClientHttpConnector method execute.

private Mono<ClientHttpResponse> execute(HttpComponentsClientHttpRequest request, HttpClientContext context) {
    AsyncRequestProducer requestProducer = request.toRequestProducer();
    return Mono.create(sink -> {
        ReactiveResponseConsumer reactiveResponseConsumer = new ReactiveResponseConsumer(new MonoFutureCallbackAdapter(sink, this.dataBufferFactory, context));
        this.client.execute(requestProducer, reactiveResponseConsumer, context, null);
    });
}
Also used : ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer)

Example 5 with ReactiveResponseConsumer

use of org.apache.hc.core5.reactive.ReactiveResponseConsumer in project httpcomponents-core by apache.

the class ReactiveClientTest method testLongRunningRequest.

@Test
public void testLongRunningRequest() throws Exception {
    final InetSocketAddress address = startClientAndServer();
    final long expectedLength = 6_554_200L;
    final AtomicReference<String> expectedHash = new AtomicReference<>();
    final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(expectedLength, expectedHash);
    final ReactiveEntityProducer producer = new ReactiveEntityProducer(stream, -1, null, null);
    final BasicRequestProducer request = getRequestProducer(address, producer);
    final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
    requester.execute(request, consumer, SOCKET_TIMEOUT, null);
    final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get(RESULT_TIMEOUT.getDuration(), RESULT_TIMEOUT.getTimeUnit());
    final StreamDescription desc = ReactiveTestUtils.consumeStream(response.getBody()).blockingGet();
    Assertions.assertEquals(expectedLength, desc.length);
    Assertions.assertEquals(expectedHash.get(), TextUtils.toHexString(desc.md.digest()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(org.reactivestreams.Publisher) ByteBuffer(java.nio.ByteBuffer) ReactiveEntityProducer(org.apache.hc.core5.reactive.ReactiveEntityProducer) StreamDescription(org.apache.hc.core5.testing.reactive.ReactiveTestUtils.StreamDescription) ReactiveResponseConsumer(org.apache.hc.core5.reactive.ReactiveResponseConsumer) Test(org.junit.Test)

Aggregations

ReactiveResponseConsumer (org.apache.hc.core5.reactive.ReactiveResponseConsumer)8 ByteBuffer (java.nio.ByteBuffer)7 ReactiveEntityProducer (org.apache.hc.core5.reactive.ReactiveEntityProducer)7 InetSocketAddress (java.net.InetSocketAddress)6 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)6 Test (org.junit.Test)6 HttpResponse (org.apache.hc.core5.http.HttpResponse)5 Publisher (org.reactivestreams.Publisher)5 ExecutionException (java.util.concurrent.ExecutionException)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 HttpStreamResetException (org.apache.hc.core5.http.HttpStreamResetException)3 SocketTimeoutException (java.net.SocketTimeoutException)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AsyncRequestProducer (org.apache.hc.core5.http.nio.AsyncRequestProducer)2 StreamDescription (org.apache.hc.core5.testing.reactive.ReactiveTestUtils.StreamDescription)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 URI (java.net.URI)1 WritableByteChannel (java.nio.channels.WritableByteChannel)1 Random (java.util.Random)1 CancellationException (java.util.concurrent.CancellationException)1