use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project mercury by yellow013.
the class AsyncClientH2Multiplexing method main.
public static void main(final String[] args) throws Exception {
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.FORCE_HTTP_2, H2Config.DEFAULT, null, ioReactorConfig);
client.start();
final HttpHost target = new HttpHost("https", "nghttp2.org");
final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
try {
final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri : requestUris) {
final SimpleHttpRequest request = SimpleRequestBuilder.get().setHttpHost(target).setPath(requestUri).build();
System.out.println("Executing request " + request);
endpoint.execute(SimpleRequestProducer.create(request), SimpleResponseConsumer.create(), new FutureCallback<SimpleHttpResponse>() {
@Override
public void completed(final SimpleHttpResponse response) {
latch.countDown();
System.out.println(request + "->" + new StatusLine(response));
System.out.println(response.getBody());
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(request + " cancelled");
}
});
}
latch.await();
} finally {
endpoint.releaseAndReuse();
}
System.out.println("Shutting down");
client.close(CloseMode.GRACEFUL);
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class HttpAsyncRequester method execute.
public void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext executeContext) {
Args.notNull(exchangeHandler, "Exchange handler");
Args.notNull(timeout, "Timeout");
Args.notNull(executeContext, "Context");
try {
exchangeHandler.produceRequest((request, entityDetails, requestContext) -> {
final String scheme = request.getScheme();
final URIAuthority authority = request.getAuthority();
if (authority == null) {
throw new ProtocolException("Request authority not specified");
}
final HttpHost target = new HttpHost(scheme, authority);
connect(target, timeout, null, new FutureCallback<AsyncClientEndpoint>() {
@Override
public void completed(final AsyncClientEndpoint endpoint) {
endpoint.execute(new AsyncClientExchangeHandler() {
@Override
public void releaseResources() {
endpoint.releaseAndDiscard();
exchangeHandler.releaseResources();
}
@Override
public void failed(final Exception cause) {
endpoint.releaseAndDiscard();
exchangeHandler.failed(cause);
}
@Override
public void cancel() {
endpoint.releaseAndDiscard();
exchangeHandler.cancel();
}
@Override
public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
channel.sendRequest(request, entityDetails, httpContext);
}
@Override
public int available() {
return exchangeHandler.available();
}
@Override
public void produce(final DataStreamChannel channel) throws IOException {
exchangeHandler.produce(channel);
}
@Override
public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
exchangeHandler.consumeInformation(response, httpContext);
}
@Override
public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
if (entityDetails == null) {
endpoint.releaseAndReuse();
}
exchangeHandler.consumeResponse(response, entityDetails, httpContext);
}
@Override
public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
exchangeHandler.updateCapacity(capacityChannel);
}
@Override
public void consume(final ByteBuffer src) throws IOException {
exchangeHandler.consume(src);
}
@Override
public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
endpoint.releaseAndReuse();
exchangeHandler.streamEnd(trailers);
}
}, pushHandlerFactory, executeContext);
}
@Override
public void failed(final Exception ex) {
exchangeHandler.failed(ex);
}
@Override
public void cancelled() {
exchangeHandler.cancel();
}
});
}, executeContext);
} catch (final IOException | HttpException ex) {
exchangeHandler.failed(ex);
}
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class Http1ServerAndRequesterTest method testSequentialRequestsSameEndpoint.
@Test
public void testSequentialRequestsSameEndpoint() throws Exception {
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
final ListenerEndpoint listener = future.get();
final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
requester.start();
final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
final Future<AsyncClientEndpoint> endpointFuture = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint endpoint = endpointFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
try {
final Future<Message<HttpResponse, String>> resultFuture1 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message1 = resultFuture1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message1, CoreMatchers.notNullValue());
final HttpResponse response1 = message1.getHead();
assertThat(response1.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body1 = message1.getBody();
assertThat(body1, CoreMatchers.equalTo("some stuff"));
final Future<Message<HttpResponse, String>> resultFuture2 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message2 = resultFuture2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message2, CoreMatchers.notNullValue());
final HttpResponse response2 = message2.getHead();
assertThat(response2.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body2 = message2.getBody();
assertThat(body2, CoreMatchers.equalTo("some other stuff"));
final Future<Message<HttpResponse, String>> resultFuture3 = endpoint.execute(new BasicRequestProducer(Method.POST, target, "/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
final Message<HttpResponse, String> message3 = resultFuture3.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message3, CoreMatchers.notNullValue());
final HttpResponse response3 = message3.getHead();
assertThat(response3.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body3 = message3.getBody();
assertThat(body3, CoreMatchers.equalTo("some more stuff"));
} finally {
endpoint.releaseAndReuse();
}
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class Http1ServerAndRequesterTest method testPipelinedRequests.
@Test
public void testPipelinedRequests() throws Exception {
server.start();
final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), scheme);
final ListenerEndpoint listener = future.get();
final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
requester.start();
final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort());
final Future<AsyncClientEndpoint> endpointFuture = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint endpoint = endpointFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
try {
final Queue<Future<Message<HttpResponse, String>>> queue = new LinkedList<>();
queue.add(endpoint.execute(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
queue.add(endpoint.execute(new BasicRequestProducer(Method.POST, target, "/other-stuff", new StringAsyncEntityProducer("some other stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
queue.add(endpoint.execute(new BasicRequestProducer(Method.POST, target, "/more-stuff", new StringAsyncEntityProducer("some more stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
while (!queue.isEmpty()) {
final Future<Message<HttpResponse, String>> resultFuture = queue.remove();
final Message<HttpResponse, String> message = resultFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
assertThat(message, CoreMatchers.notNullValue());
final HttpResponse response = message.getHead();
assertThat(response.getCode(), CoreMatchers.equalTo(HttpStatus.SC_OK));
final String body = message.getBody();
assertThat(body, CoreMatchers.containsString("stuff"));
}
} finally {
endpoint.releaseAndReuse();
}
}
use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.
the class H2CompatibilityTest method executeH2.
void executeH2(final HttpHost target) throws Exception {
{
System.out.println("*** HTTP/2 simple request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final CountDownLatch countDownLatch = new CountDownLatch(1);
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
countDownLatch.countDown();
}
});
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(single request execution failed to complete in time)");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
{
System.out.println("*** HTTP/2 multiplexed request execution ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final int reqCount = 20;
final CountDownLatch countDownLatch = new CountDownLatch(reqCount);
for (int i = 0; i < reqCount; i++) {
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/status.html");
endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {
@Override
public void completed(final Message<HttpResponse, String> responseMessage) {
final HttpResponse response = responseMessage.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, "multiplexed / " + response.getFirstHeader("server"));
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
countDownLatch.countDown();
}
@Override
public void failed(final Exception ex) {
logResult(TestResult.NOK, target, httpget, null, "(" + ex.getMessage() + ")");
countDownLatch.countDown();
}
@Override
public void cancelled() {
logResult(TestResult.NOK, target, httpget, null, "(cancelled)");
countDownLatch.countDown();
}
});
}
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "(multiplexed request execution failed to complete in time)");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
{
System.out.println("*** HTTP/2 request execution with push ***");
final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
try {
final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final CountDownLatch countDownLatch = new CountDownLatch(5);
final HttpRequest httpget = new BasicHttpRequest(Method.GET, target, "/index.html");
final Future<Message<HttpResponse, String>> future = endpoint.execute(new BasicRequestProducer(httpget, null), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, Void>>(new BasicResponseConsumer<>(new DiscardingEntityConsumer<>())) {
@Override
protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, Void> responseMessage) throws IOException, HttpException {
final HttpResponse response = responseMessage.getHead();
logResult(TestResult.OK, target, promise, response, "pushed / " + response.getFirstHeader("server"));
countDownLatch.countDown();
}
@Override
protected void handleError(final HttpRequest promise, final Exception cause) {
logResult(TestResult.NOK, target, promise, null, "(" + cause.getMessage() + ")");
countDownLatch.countDown();
}
}, null, null);
final Message<HttpResponse, String> message = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
final HttpResponse response = message.getHead();
final int code = response.getCode();
if (code == HttpStatus.SC_OK) {
logResult(TestResult.OK, target, httpget, response, Objects.toString(response.getFirstHeader("server")));
if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
logResult(TestResult.NOK, target, null, null, "Push messages not received");
}
} else {
logResult(TestResult.NOK, target, httpget, response, "(status " + code + ")");
}
} catch (final ExecutionException ex) {
final Throwable cause = ex.getCause();
logResult(TestResult.NOK, target, null, null, "(" + cause.getMessage() + ")");
} catch (final TimeoutException ex) {
logResult(TestResult.NOK, target, null, null, "(time out)");
}
}
}
Aggregations