Search in sources :

Example 1 with BasicResponseProducer

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

the class H2IntegrationTest method testPrematureResponse.

@Test
public void testPrematureResponse() throws Exception {
    server.register("*", new Supplier<AsyncServerExchangeHandler>() {

        @Override
        public AsyncServerExchangeHandler get() {
            return new AsyncServerExchangeHandler() {

                private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();

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

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

                @Override
                public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                }

                @Override
                public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
                    final AsyncResponseProducer producer;
                    final Header h = request.getFirstHeader("password");
                    if (h != null && "secret".equals(h.getValue())) {
                        producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
                    } else {
                        producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
                    }
                    responseProducer.set(producer);
                    producer.sendResponse(responseChannel, context);
                }

                @Override
                public int available() {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    return producer.available();
                }

                @Override
                public void produce(final DataStreamChannel channel) throws IOException {
                    final AsyncResponseProducer producer = this.responseProducer.get();
                    producer.produce(channel);
                }

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

                @Override
                public void releaseResources() {
                }
            };
        }
    });
    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.POST, createRequestURI(serverEndpoint, "/echo"));
    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(HttpStatus.SC_UNAUTHORIZED, response1.getCode());
    Assertions.assertNotNull("You shall not pass", result1.getBody());
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) 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) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) 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) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 2 with BasicResponseProducer

use of org.apache.hc.core5.http.nio.support.BasicResponseProducer 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 3 with BasicResponseProducer

use of org.apache.hc.core5.http.nio.support.BasicResponseProducer 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 4 with BasicResponseProducer

use of org.apache.hc.core5.http.nio.support.BasicResponseProducer 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 5 with BasicResponseProducer

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

the class ServerH2StreamHandler method handle.

@Override
public void handle(final HttpException ex, final boolean endStream) throws HttpException, IOException {
    if (done.get()) {
        throw ex;
    }
    switch(requestState) {
        case HEADERS:
            requestState = endStream ? MessageState.COMPLETE : MessageState.BODY;
            if (!responseCommitted.get()) {
                final AsyncResponseProducer responseProducer = new BasicResponseProducer(ServerSupport.toStatusCode(ex), ServerSupport.toErrorMessage(ex));
                exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
                exchangeHandler.handleRequest(null, null, responseChannel, context);
            } else {
                throw ex;
            }
            break;
        case BODY:
            responseState = MessageState.COMPLETE;
        default:
            throw ex;
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer)

Aggregations

BasicResponseProducer (org.apache.hc.core5.http.nio.support.BasicResponseProducer)14 HttpException (org.apache.hc.core5.http.HttpException)13 HttpResponse (org.apache.hc.core5.http.HttpResponse)13 HttpRequest (org.apache.hc.core5.http.HttpRequest)12 IOException (java.io.IOException)11 AsyncResponseProducer (org.apache.hc.core5.http.nio.AsyncResponseProducer)11 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)11 InterruptedIOException (java.io.InterruptedIOException)10 InetSocketAddress (java.net.InetSocketAddress)10 Message (org.apache.hc.core5.http.Message)10 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)10 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)10 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)10 Test (org.junit.Test)10 Header (org.apache.hc.core5.http.Header)9 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)9 AsyncServerRequestHandler (org.apache.hc.core5.http.nio.AsyncServerRequestHandler)8 EntityDetails (org.apache.hc.core5.http.EntityDetails)7 ProtocolException (org.apache.hc.core5.http.ProtocolException)7 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)7