Search in sources :

Example 11 with BasicResponseConsumer

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

the class H2IntegrationTest method testPushRefused.

@Test
public void testPushRefused() throws Exception {
    final BlockingQueue<Exception> pushResultQueue = new LinkedBlockingDeque<>();
    final InetSocketAddress serverEndpoint = server.start();
    server.register("/hello", new Supplier<AsyncServerExchangeHandler>() {

        @Override
        public AsyncServerExchangeHandler get() {
            return 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(AsyncEntityProducers.create("Pushing all sorts of stuff")) {

                        @Override
                        public void failed(final Exception cause) {
                            pushResultQueue.add(cause);
                            super.failed(cause);
                        }
                    });
                    responseTrigger.pushPromise(new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/more-stuff")), context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)) {

                        @Override
                        public void failed(final Exception cause) {
                            pushResultQueue.add(cause);
                            super.failed(cause);
                        }
                    });
                    responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, AsyncEntityProducers.create("Hi there")), context);
                }
            };
        }
    });
    client.start(H2Config.custom().setPushEnabled(true).build());
    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()), 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 Object result2 = pushResultQueue.poll(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result2);
    Assertions.assertTrue(result2 instanceof H2StreamResetException);
    Assertions.assertEquals(H2Error.REFUSED_STREAM.getCode(), ((H2StreamResetException) result2).getCode());
    final Object result3 = pushResultQueue.poll(5, TimeUnit.SECONDS);
    Assertions.assertNotNull(result3);
    Assertions.assertTrue(result3 instanceof H2StreamResetException);
    Assertions.assertEquals(H2Error.REFUSED_STREAM.getCode(), ((H2StreamResetException) result3).getCode());
}
Also used : LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) 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) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 12 with BasicResponseConsumer

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

the class H2IntegrationTest method testExpectationFailed.

@Test
public void testExpectationFailed() throws Exception {
    server.register("*", () -> new MessageExchangeHandler<String>(new StringAsyncEntityConsumer()) {

        @Override
        protected void handle(final Message<HttpRequest, String> request, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws IOException, HttpException {
            responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, "All is well"), context);
        }
    });
    final InetSocketAddress serverEndpoint = server.start(null, handler -> new BasicAsyncServerExpectationDecorator(handler) {

        @Override
        protected AsyncResponseProducer verify(final HttpRequest request, final HttpContext context) throws IOException, HttpException {
            final Header h = request.getFirstHeader("password");
            if (h != null && "secret".equals(h.getValue())) {
                return null;
            } else {
                return new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
            }
        }
    }, H2Config.DEFAULT);
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
    request1.addHeader("password", "secret");
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcdef", 5000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    Assertions.assertNotNull("All is well", result1.getBody());
    final HttpRequest request2 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
    final Future<Message<HttpResponse, String>> future2 = streamEndpoint.execute(new BasicRequestProducer(request2, new MultiLineEntityProducer("0123456789abcdef", 5000)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result2 = future2.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result2);
    final HttpResponse response2 = result2.getHead();
    Assertions.assertNotNull(response2);
    Assertions.assertEquals(HttpStatus.SC_UNAUTHORIZED, response2.getCode());
    Assertions.assertNotNull("You shall not pass", result2.getBody());
}
Also used : BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) HttpException(org.apache.hc.core5.http.HttpException) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) 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) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 13 with BasicResponseConsumer

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

the class H2IntegrationTest method testMessageWithTrailers.

@Test
public void testMessageWithTrailers() throws Exception {
    server.register("/hello", () -> new AbstractServerExchangeHandler<Message<HttpRequest, String>>() {

        @Override
        protected AsyncRequestConsumer<Message<HttpRequest, String>> supplyConsumer(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context) throws HttpException {
            return new BasicRequestConsumer<>(entityDetails != null ? new StringAsyncEntityConsumer() : null);
        }

        @Override
        protected void handle(final Message<HttpRequest, String> requestMessage, final AsyncServerRequestHandler.ResponseTrigger responseTrigger, final HttpContext context) throws HttpException, IOException {
            responseTrigger.submitResponse(new BasicResponseProducer(HttpStatus.SC_OK, new DigestingEntityProducer("MD5", new StringAsyncEntityProducer("Hello back with some trailers"))), context);
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
    final DigestingEntityConsumer<String> entityConsumer = new DigestingEntityConsumer<>("MD5", new StringAsyncEntityConsumer());
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, null), new BasicResponseConsumer<>(entityConsumer), null);
    final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result1);
    final HttpResponse response1 = result1.getHead();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(200, response1.getCode());
    Assertions.assertEquals("Hello back with some trailers", result1.getBody());
    final List<Header> trailers = entityConsumer.getTrailers();
    Assertions.assertNotNull(trailers);
    Assertions.assertEquals(2, trailers.size());
    final Map<String, String> map = new HashMap<>();
    for (final Header header : trailers) {
        map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
    }
    final String digest = TextUtils.toHexString(entityConsumer.getDigest());
    Assertions.assertEquals("MD5", map.get("digest-algo"));
    Assertions.assertEquals(digest, map.get("digest"));
}
Also used : Message(org.apache.hc.core5.http.Message) DigestingEntityProducer(org.apache.hc.core5.http.nio.entity.DigestingEntityProducer) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) EntityDetails(org.apache.hc.core5.http.EntityDetails) 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) DigestingEntityConsumer(org.apache.hc.core5.http.nio.entity.DigestingEntityConsumer) 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) AsyncRequestConsumer(org.apache.hc.core5.http.nio.AsyncRequestConsumer) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 14 with BasicResponseConsumer

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

the class H2IntegrationTest method testBasicPost.

@Test
public void testBasicPost() throws Exception {
    server.register("/hello", () -> new SingleLineResponseHandler("Hi back"));
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Queue<Future<Message<HttpResponse, String>>> queue = new LinkedList<>();
    for (int i = 0; i < 10; i++) {
        final HttpRequest request = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/hello"));
        queue.add(streamEndpoint.execute(new BasicRequestProducer(request, new StringAsyncEntityProducer("Hi there", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
    }
    while (!queue.isEmpty()) {
        final Future<Message<HttpResponse, String>> future = queue.remove();
        final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
        Assertions.assertNotNull(result);
        final HttpResponse response = result.getHead();
        final String entity1 = result.getBody();
        Assertions.assertNotNull(response);
        Assertions.assertEquals(200, response.getCode());
        Assertions.assertEquals("Hi back", entity1);
    }
}
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) 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) LinkedList(java.util.LinkedList) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) Future(java.util.concurrent.Future) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) Test(org.junit.Test)

Example 15 with BasicResponseConsumer

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

the class H2FullDuplexClientExample 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 H2Config h2Config = H2Config.custom().setPushEnabled(false).setMaxConcurrentStreams(100).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final URI requestUri = new URI("http://nghttp2.org/httpbin/post");
    final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    final CountDownLatch latch = new CountDownLatch(1);
    requester.execute(new AsyncClientExchangeHandler() {

        @Override
        public void releaseResources() {
            requestProducer.releaseResources();
            responseConsumer.releaseResources();
            latch.countDown();
        }

        @Override
        public void cancel() {
            System.out.println(requestUri + " cancelled");
        }

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

        @Override
        public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
            requestProducer.sendRequest(channel, httpContext);
        }

        @Override
        public int available() {
            return requestProducer.available();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            requestProducer.produce(channel);
        }

        @Override
        public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
            responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            responseConsumer.updateCapacity(capacityChannel);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            responseConsumer.consume(src);
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            responseConsumer.streamEnd(trailers);
        }
    }, Timeout.ofSeconds(30), HttpCoreContext.create());
    latch.await();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpConnection(org.apache.hc.core5.http.HttpConnection) URI(java.net.URI) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) Header(org.apache.hc.core5.http.Header) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) H2Config(org.apache.hc.core5.http2.config.H2Config)

Aggregations

StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)94 Message (org.apache.hc.core5.http.Message)93 HttpResponse (org.apache.hc.core5.http.HttpResponse)92 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)86 InetSocketAddress (java.net.InetSocketAddress)84 Test (org.junit.Test)73 HttpRequest (org.apache.hc.core5.http.HttpRequest)41 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)40 HttpHost (org.apache.hc.core5.http.HttpHost)38 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)36 StringAsyncEntityProducer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer)30 IOException (java.io.IOException)27 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)26 HttpException (org.apache.hc.core5.http.HttpException)25 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)23 InterruptedIOException (java.io.InterruptedIOException)22 Header (org.apache.hc.core5.http.Header)20 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)20 Future (java.util.concurrent.Future)18 ExecutionException (java.util.concurrent.ExecutionException)17