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();
}
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);
}
}
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()));
}
}
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);
});
}
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()));
}
Aggregations