Search in sources :

Example 6 with ResponseChannel

use of org.apache.hc.core5.http.nio.ResponseChannel 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)

Example 7 with ResponseChannel

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

the class Http1IntegrationTest method testDelayedExpectationVerification.

@Test
public void testDelayedExpectationVerification() throws Exception {
    server.register("*", () -> new AsyncServerExchangeHandler() {

        private final Random random = new Random(System.currentTimeMillis());

        private final AsyncEntityProducer entityProducer = AsyncEntityProducers.create("All is well");

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            Executors.newSingleThreadExecutor().execute(() -> {
                try {
                    if (entityDetails != null) {
                        final Header h = request.getFirstHeader(HttpHeaders.EXPECT);
                        if (h != null && HeaderElements.CONTINUE.equalsIgnoreCase(h.getValue())) {
                            Thread.sleep(random.nextInt(1000));
                            responseChannel.sendInformation(new BasicHttpResponse(HttpStatus.SC_CONTINUE), context);
                        }
                        final HttpResponse response = new BasicHttpResponse(200);
                        synchronized (entityProducer) {
                            responseChannel.sendResponse(response, entityProducer, context);
                        }
                    }
                } catch (final Exception ignore) {
                // ignore
                }
            });
        }

        @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 int available() {
            synchronized (entityProducer) {
                return entityProducer.available();
            }
        }

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

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

        @Override
        public void releaseResources() {
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start(Http1Config.custom().setWaitForContinueTimeout(Timeout.ofMilliseconds(100)).build());
    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 < 5; i++) {
        queue.add(streamEndpoint.execute(new BasicRequestProducer(Method.POST, createRequestURI(serverEndpoint, "/"), AsyncEntityProducers.create("Some important message")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null));
    }
    while (!queue.isEmpty()) {
        final Future<Message<HttpResponse, String>> future = queue.remove();
        final Message<HttpResponse, String> result = future.get(LONG_TIMEOUT.getDuration(), LONG_TIMEOUT.getTimeUnit());
        Assertions.assertNotNull(result);
        final HttpResponse response = result.getHead();
        Assertions.assertNotNull(response);
        Assertions.assertEquals(200, response.getCode());
        Assertions.assertNotNull("All is well", result.getBody());
    }
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) Random(java.util.Random) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) 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) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CancellationException(java.util.concurrent.CancellationException) MalformedChunkCodingException(org.apache.hc.core5.http.MalformedChunkCodingException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) LinkedList(java.util.LinkedList) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) Future(java.util.concurrent.Future) Test(org.junit.Test)

Example 8 with ResponseChannel

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

the class TerminalAsyncServerFilter method handle.

@Override
public AsyncDataConsumer handle(final HttpRequest request, final EntityDetails entityDetails, final HttpContext context, final AsyncFilterChain.ResponseTrigger responseTrigger, final AsyncFilterChain chain) throws HttpException, IOException {
    final AsyncServerExchangeHandler exchangeHandler = handlerFactory.create(request, context);
    if (exchangeHandler != null) {
        exchangeHandler.handleRequest(request, entityDetails, new ResponseChannel() {

            @Override
            public void sendInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.sendInformation(response);
            }

            @Override
            public void sendResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.submitResponse(response, entityDetails != null ? new AsyncEntityProducer() {

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

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public long getContentLength() {
                        return entityDetails.getContentLength();
                    }

                    @Override
                    public String getContentType() {
                        return entityDetails.getContentType();
                    }

                    @Override
                    public String getContentEncoding() {
                        return entityDetails.getContentEncoding();
                    }

                    @Override
                    public boolean isChunked() {
                        return entityDetails.isChunked();
                    }

                    @Override
                    public Set<String> getTrailerNames() {
                        return entityDetails.getTrailerNames();
                    }

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

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

                    @Override
                    public void releaseResources() {
                        exchangeHandler.releaseResources();
                    }
                } : null);
            }

            @Override
            public void pushPromise(final HttpRequest promise, final AsyncPushProducer pushProducer, final HttpContext httpContext) throws HttpException, IOException {
                responseTrigger.pushPromise(promise, pushProducer);
            }
        }, context);
        return exchangeHandler;
    }
    responseTrigger.submitResponse(new BasicHttpResponse(HttpStatus.SC_NOT_FOUND), AsyncEntityProducers.create("Not found"));
    return null;
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) Set(java.util.Set) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 9 with ResponseChannel

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

the class AsyncServerFilterChainExchangeHandlerFactory method create.

@Override
public AsyncServerExchangeHandler create(final HttpRequest request, final HttpContext context) throws HttpException {
    return new AsyncServerExchangeHandler() {

        private final AtomicReference<AsyncDataConsumer> dataConsumerRef = new AtomicReference<>();

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

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            dataConsumerRef.set(filterChain.handle(request, entityDetails, context, new AsyncFilterChain.ResponseTrigger() {

                @Override
                public void sendInformation(final HttpResponse response) throws HttpException, IOException {
                    responseChannel.sendInformation(response, context);
                }

                @Override
                public void submitResponse(final HttpResponse response, final AsyncEntityProducer entityProducer) throws HttpException, IOException {
                    final AsyncResponseProducer responseProducer = new BasicResponseProducer(response, entityProducer);
                    responseProducerRef.set(responseProducer);
                    responseProducer.sendResponse(responseChannel, context);
                }

                @Override
                public void pushPromise(final HttpRequest promise, final AsyncPushProducer responseProducer) throws HttpException, IOException {
                    responseChannel.pushPromise(promise, responseProducer, context);
                }
            }));
        }

        @Override
        public void failed(final Exception cause) {
            if (exceptionCallback != null) {
                exceptionCallback.execute(cause);
            }
            final AsyncResponseProducer handler = responseProducerRef.get();
            if (handler != null) {
                handler.failed(cause);
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.updateCapacity(capacityChannel);
            } else {
                capacityChannel.update(Integer.MAX_VALUE);
            }
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.consume(src);
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.get();
            if (dataConsumer != null) {
                dataConsumer.streamEnd(trailers);
            }
        }

        @Override
        public int available() {
            final AsyncResponseProducer responseProducer = responseProducerRef.get();
            Asserts.notNull(responseProducer, "Response producer");
            return responseProducer.available();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            final AsyncResponseProducer responseProducer = responseProducerRef.get();
            Asserts.notNull(responseProducer, "Response producer");
            responseProducer.produce(channel);
        }

        @Override
        public void releaseResources() {
            final AsyncDataConsumer dataConsumer = dataConsumerRef.getAndSet(null);
            if (dataConsumer != null) {
                dataConsumer.releaseResources();
            }
            final AsyncResponseProducer responseProducer = responseProducerRef.getAndSet(null);
            if (responseProducer != null) {
                responseProducer.releaseResources();
            }
        }
    };
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) AsyncPushProducer(org.apache.hc.core5.http.nio.AsyncPushProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) Header(org.apache.hc.core5.http.Header) EntityDetails(org.apache.hc.core5.http.EntityDetails) AsyncDataConsumer(org.apache.hc.core5.http.nio.AsyncDataConsumer) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 10 with ResponseChannel

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

the class BasicAsyncServerExpectationDecorator method handleRequest.

@Override
public final void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
    if (entityDetails != null) {
        final Header h = request.getFirstHeader(HttpHeaders.EXPECT);
        if (h != null && HeaderElements.CONTINUE.equalsIgnoreCase(h.getValue())) {
            final AsyncResponseProducer producer = verify(request, context);
            if (producer != null) {
                responseProducerRef.set(producer);
                producer.sendResponse(responseChannel, context);
                return;
            }
            responseChannel.sendInformation(new BasicHttpResponse(HttpStatus.SC_CONTINUE), context);
        }
    }
    handler.handleRequest(request, entityDetails, responseChannel, context);
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header)

Aggregations

HttpResponse (org.apache.hc.core5.http.HttpResponse)15 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)14 HttpException (org.apache.hc.core5.http.HttpException)12 EntityDetails (org.apache.hc.core5.http.EntityDetails)11 HttpRequest (org.apache.hc.core5.http.HttpRequest)11 IOException (java.io.IOException)10 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)10 ResponseChannel (org.apache.hc.core5.http.nio.ResponseChannel)9 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)9 ByteBuffer (java.nio.ByteBuffer)8 Header (org.apache.hc.core5.http.Header)8 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 AsyncResponseProducer (org.apache.hc.core5.http.nio.AsyncResponseProducer)8 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)8 InetSocketAddress (java.net.InetSocketAddress)7 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)7 BasicResponseProducer (org.apache.hc.core5.http.nio.support.BasicResponseProducer)6 URISyntaxException (java.net.URISyntaxException)5 InterruptedIOException (java.io.InterruptedIOException)4 ExecutionException (java.util.concurrent.ExecutionException)4