Search in sources :

Example 1 with AbstractAsyncPushHandler

use of org.apache.hc.core5.http.nio.support.AbstractAsyncPushHandler 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)");
        }
    }
}
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) Arrays(java.util.Arrays) H2Config(org.apache.hc.core5.http2.config.H2Config) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) LoggingConnPoolListener(org.apache.hc.core5.testing.classic.LoggingConnPoolListener) TimeoutException(java.util.concurrent.TimeoutException) AbstractAsyncPushHandler(org.apache.hc.core5.http.nio.support.AbstractAsyncPushHandler) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) LoggingIOSessionListener(org.apache.hc.core5.testing.nio.LoggingIOSessionListener) TextUtils(org.apache.hc.core5.util.TextUtils) Future(java.util.concurrent.Future) LoggingHttp1StreamListener(org.apache.hc.core5.testing.nio.LoggingHttp1StreamListener) CodingErrorAction(java.nio.charset.CodingErrorAction) CloseMode(org.apache.hc.core5.io.CloseMode) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpException(org.apache.hc.core5.http.HttpException) Message(org.apache.hc.core5.http.Message) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) LoggingH2StreamListener(org.apache.hc.core5.testing.nio.LoggingH2StreamListener) H2RequesterBootstrap(org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) IOException(java.io.IOException) LoggingIOSessionDecorator(org.apache.hc.core5.testing.nio.LoggingIOSessionDecorator) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) Timeout(org.apache.hc.core5.util.Timeout) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) HttpHost(org.apache.hc.core5.http.HttpHost) LoggingExceptionCallback(org.apache.hc.core5.testing.nio.LoggingExceptionCallback) HttpRequest(org.apache.hc.core5.http.HttpRequest) ContentType(org.apache.hc.core5.http.ContentType) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) Method(org.apache.hc.core5.http.Method) HttpStatus(org.apache.hc.core5.http.HttpStatus) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) Message(org.apache.hc.core5.http.Message) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractAsyncPushHandler(org.apache.hc.core5.http.nio.support.AbstractAsyncPushHandler) 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) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) Future(java.util.concurrent.Future) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with AbstractAsyncPushHandler

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

the class H2IntegrationTest method testPush.

@Test
public void testPush() throws Exception {
    final InetSocketAddress serverEndpoint = server.start();
    server.register("/hello", () -> new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {

        @Override
        protected void handle(final Message<HttpRequest, Void> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")), context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)));
            responseTrigger.submitResponse(AsyncResponseBuilder.create(HttpStatus.SC_OK).setEntity("Hi there", ContentType.TEXT_PLAIN).build(), context);
        }
    });
    client.start(H2Config.custom().setPushEnabled(true).build());
    final BlockingQueue<Message<HttpResponse, String>> pushMessageQueue = new LinkedBlockingDeque<>();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/hello")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), (request, context) -> new AbstractAsyncPushHandler<Message<HttpResponse, String>>(new BasicResponseConsumer<>(new StringAsyncEntityConsumer())) {

        @Override
        protected void handleResponse(final HttpRequest promise, final Message<HttpResponse, String> responseMessage) throws IOException, HttpException {
            try {
                pushMessageQueue.put(responseMessage);
            } catch (final InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException(ex.getMessage());
            }
        }
    }, null, null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    final String entity1 = result1.getBody();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    Assertions.assertEquals("Hi there", entity1);
    final Message<HttpResponse, String> result2 = pushMessageQueue.poll(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result2);
    final HttpResponse response2 = result2.getHead();
    final String entity2 = result2.getBody();
    Assertions.assertEquals(200, response2.getCode());
    Assertions.assertNotNull(entity2);
    final StringTokenizer t1 = new StringTokenizer(entity2, "\r\n");
    while (t1.hasMoreTokens()) {
        Assertions.assertEquals("Pushing lots of stuff", t1.nextToken());
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicPushProducer(org.apache.hc.core5.http.nio.support.BasicPushProducer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) StringTokenizer(java.util.StringTokenizer) Test(org.junit.Test)

Aggregations

IOException (java.io.IOException)2 HttpException (org.apache.hc.core5.http.HttpException)2 HttpRequest (org.apache.hc.core5.http.HttpRequest)2 HttpResponse (org.apache.hc.core5.http.HttpResponse)2 Message (org.apache.hc.core5.http.Message)2 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)2 DiscardingEntityConsumer (org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer)2 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)2 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)2 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)2 InterruptedIOException (java.io.InterruptedIOException)1 InetSocketAddress (java.net.InetSocketAddress)1 CodingErrorAction (java.nio.charset.CodingErrorAction)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Objects (java.util.Objects)1 StringTokenizer (java.util.StringTokenizer)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1