Search in sources :

Example 11 with AsyncClientEndpoint

use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.

the class H2CompatibilityTest method executeHttpBin.

void executeHttpBin(final HttpHost target) throws Exception {
    {
        System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***");
        final List<Message<HttpRequest, AsyncEntityProducer>> requestMessages = Arrays.asList(new Message<>(new BasicHttpRequest(Method.GET, target, "/headers"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.GET, target, "/drip"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000"), null), new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2"), null), new Message<>(new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>(new BasicHttpRequest(Method.PUT, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)));
        for (final Message<HttpRequest, AsyncEntityProducer> message : requestMessages) {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            final HttpRequest request = message.getHead();
            final AsyncEntityProducer entityProducer = message.getBody();
            client.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), TIMEOUT, 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, request, response, Objects.toString(response.getFirstHeader("server")));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
            if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
                logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
            }
        }
    }
    {
        System.out.println("*** httpbin.org HTTP/1.1 pipelined request execution ***");
        final Future<AsyncClientEndpoint> connectFuture = client.connect(target, TIMEOUT);
        final AsyncClientEndpoint streamEndpoint = connectFuture.get();
        final int n = 10;
        final CountDownLatch countDownLatch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            final HttpRequest request;
            final AsyncEntityProducer entityProducer;
            if (i % 2 == 0) {
                request = new BasicHttpRequest(Method.GET, target, "/headers");
                entityProducer = null;
            } else {
                request = new BasicHttpRequest(Method.POST, target, "/anything");
                entityProducer = new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN);
            }
            streamEndpoint.execute(new BasicRequestProducer(request, entityProducer), new BasicResponseConsumer<>(new StringAsyncEntityConsumer(CharCodingConfig.custom().setCharset(StandardCharsets.US_ASCII).setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.REPLACE).build())), 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, request, response, "pipelined / " + response.getFirstHeader("server"));
                    } else {
                        logResult(TestResult.NOK, target, request, response, "(status " + code + ")");
                    }
                    countDownLatch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    logResult(TestResult.NOK, target, request, null, "(" + ex.getMessage() + ")");
                    countDownLatch.countDown();
                }

                @Override
                public void cancelled() {
                    logResult(TestResult.NOK, target, request, null, "(cancelled)");
                    countDownLatch.countDown();
                }
            });
        }
        if (!countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())) {
            logResult(TestResult.NOK, target, null, null, "(httpbin.org tests failed to complete in time)");
        }
    }
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) TimeoutException(java.util.concurrent.TimeoutException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Future(java.util.concurrent.Future) List(java.util.List) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 12 with AsyncClientEndpoint

use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.

the class H2ProtocolNegotiationTest method testForceHttp2.

@Test
public void testForceHttp2() throws Exception {
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(0), URIScheme.HTTPS);
    final ListenerEndpoint listener = future.get();
    final InetSocketAddress address = (InetSocketAddress) listener.getAddress();
    requester.start();
    final HttpHost target = new HttpHost(URIScheme.HTTPS.id, "localhost", address.getPort());
    final Future<AsyncClientEndpoint> connectFuture = requester.connect(target, TIMEOUT, HttpVersionPolicy.FORCE_HTTP_2, null);
    final AsyncClientEndpoint endpoint = connectFuture.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    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));
    assertThat(response1.getVersion(), CoreMatchers.equalTo(HttpVersion.HTTP_2));
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.jupiter.api.Test)

Example 13 with AsyncClientEndpoint

use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.

the class H2ServerAndRequesterTest 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();
    }
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) InetSocketAddress(java.net.InetSocketAddress) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) HttpHost(org.apache.hc.core5.http.HttpHost) Test(org.junit.Test)

Example 14 with AsyncClientEndpoint

use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.

the class AsyncPipelinedRequestExecutionExample method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
    // Create and start requester
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).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 HttpHost target = new HttpHost("httpbin.org");
    final String[] requestUris = new String[] { "/", "/ip", "/user-agent", "/headers" };
    final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
    final AsyncClientEndpoint clientEndpoint = future.get();
    final CountDownLatch latch = new CountDownLatch(requestUris.length);
    for (final String requestUri : requestUris) {
        clientEndpoint.execute(AsyncRequestBuilder.get().setHttpHost(target).setPath(requestUri).build(), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

            @Override
            public void completed(final Message<HttpResponse, String> message) {
                latch.countDown();
                final HttpResponse response = message.getHead();
                final String body = message.getBody();
                System.out.println(requestUri + "->" + response.getCode());
                System.out.println(body);
            }

            @Override
            public void failed(final Exception ex) {
                latch.countDown();
                System.out.println(requestUri + "->" + ex);
            }

            @Override
            public void cancelled() {
                latch.countDown();
                System.out.println(requestUri + " cancelled");
            }
        });
    }
    latch.await();
    // Manually release client endpoint when done !!!
    clientEndpoint.releaseAndDiscard();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 15 with AsyncClientEndpoint

use of org.apache.hc.core5.http.nio.AsyncClientEndpoint in project httpcomponents-core by apache.

the class BenchmarkWorker method execute.

public void execute() {
    if (requestCount.decrementAndGet() >= 0) {
        AsyncClientEndpoint endpoint = endpointRef.get();
        if (endpoint != null && !endpoint.isConnected()) {
            endpoint.releaseAndDiscard();
            endpoint = null;
        }
        if (endpoint == null) {
            requester.connect(host, config.getSocketTimeout(), null, new FutureCallback<AsyncClientEndpoint>() {

                @Override
                public void completed(final AsyncClientEndpoint endpoint) {
                    endpointRef.set(endpoint);
                    endpoint.execute(createRequestProducer(), createResponseConsumer(), context, new FutureCallback<Void>() {

                        @Override
                        public void completed(final Void result) {
                            execute();
                        }

                        @Override
                        public void failed(final Exception cause) {
                            execute();
                        }

                        @Override
                        public void cancelled() {
                            completionLatch.countDown();
                        }
                    });
                }

                @Override
                public void failed(final Exception cause) {
                    stats.incFailureCount();
                    if (config.getVerbosity() >= 1) {
                        System.out.println("Connect error: " + cause.getMessage());
                    }
                    execute();
                }

                @Override
                public void cancelled() {
                    completionLatch.countDown();
                }
            });
        } else {
            stats.incKeepAliveCount();
            endpoint.execute(createRequestProducer(), createResponseConsumer(), context, new FutureCallback<Void>() {

                @Override
                public void completed(final Void result) {
                    execute();
                }

                @Override
                public void failed(final Exception cause) {
                    execute();
                }

                @Override
                public void cancelled() {
                    completionLatch.countDown();
                }
            });
        }
    } else {
        completionLatch.countDown();
    }
}
Also used : AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException)

Aggregations

AsyncClientEndpoint (org.apache.hc.core5.http.nio.AsyncClientEndpoint)19 HttpHost (org.apache.hc.core5.http.HttpHost)17 HttpResponse (org.apache.hc.core5.http.HttpResponse)16 Message (org.apache.hc.core5.http.Message)15 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)15 CountDownLatch (java.util.concurrent.CountDownLatch)10 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)10 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)9 List (java.util.List)8 InetSocketAddress (java.net.InetSocketAddress)7 HttpAsyncRequester (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)7 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)7 Header (org.apache.hc.core5.http.Header)6 HttpConnection (org.apache.hc.core5.http.HttpConnection)6 H2Config (org.apache.hc.core5.http2.config.H2Config)6 Future (java.util.concurrent.Future)5 HttpException (org.apache.hc.core5.http.HttpException)5 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)5 RawFrame (org.apache.hc.core5.http2.frame.RawFrame)5 H2StreamListener (org.apache.hc.core5.http2.impl.nio.H2StreamListener)5