Search in sources :

Example 11 with BasicResponseProducer

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

the class AsyncResponseBuilder method build.

@Override
public AsyncResponseProducer build() {
    final BasicHttpResponse response = new BasicHttpResponse(getStatus());
    response.setVersion(getVersion());
    response.setHeaders(getHeaders());
    return new BasicResponseProducer(response, entityProducer);
}
Also used : BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse)

Example 12 with BasicResponseProducer

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

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

the class ServerHttp1StreamHandler method terminateExchange.

void terminateExchange(final HttpException ex) throws HttpException, IOException {
    if (done.get() || requestState != MessageState.HEADERS) {
        throw new ProtocolException("Unexpected message head");
    }
    receivedRequest = null;
    requestState = MessageState.COMPLETE;
    final HttpResponse response = new BasicHttpResponse(ServerSupport.toStatusCode(ex));
    response.addHeader(HttpHeaders.CONNECTION, HeaderElements.CLOSE);
    final AsyncResponseProducer responseProducer = new BasicResponseProducer(response, ServerSupport.toErrorMessage(ex));
    exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
    exchangeHandler.handleRequest(null, null, responseChannel, context);
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ProtocolException(org.apache.hc.core5.http.ProtocolException) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer)

Example 14 with BasicResponseProducer

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

the class Http1IntegrationTest method testPrematureResponse.

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

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

        @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 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() {
            final AsyncResponseProducer producer = responseProducer.get();
            return producer.available();
        }

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            final AsyncResponseProducer producer = 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();
    for (int i = 0; i < 3; i++) {
        final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
        final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiLineEntityProducer("0123456789abcdef", 100000)), 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());
        Assertions.assertTrue(streamEndpoint.isOpen());
    }
    final HttpRequest request1 = new BasicHttpRequest(Method.POST, createRequestURI(serverEndpoint, "/echo"));
    final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(new BasicRequestProducer(request1, new MultiBinEntityProducer(new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }, 100000, ContentType.TEXT_PLAIN)), 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());
    Assertions.assertFalse(streamEndpoint.isOpen());
}
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) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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) Header(org.apache.hc.core5.http.Header) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) Test(org.junit.Test)

Example 15 with BasicResponseProducer

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

the class ServerH2StreamHandler method consumeHeader.

@Override
public void consumeHeader(final List<Header> headers, final boolean endStream) throws HttpException, IOException {
    if (done.get()) {
        throw new ProtocolException("Unexpected message headers");
    }
    switch(requestState) {
        case HEADERS:
            requestState = endStream ? MessageState.COMPLETE : MessageState.BODY;
            final HttpRequest request = DefaultH2RequestConverter.INSTANCE.convert(headers);
            final EntityDetails requestEntityDetails = endStream ? null : new IncomingEntityDetails(request, -1);
            final AsyncServerExchangeHandler handler;
            try {
                handler = exchangeHandlerFactory != null ? exchangeHandlerFactory.create(request, context) : null;
            } catch (final ProtocolException ex) {
                throw new H2StreamResetException(H2Error.PROTOCOL_ERROR, ex.getMessage());
            }
            if (handler == null) {
                throw new H2StreamResetException(H2Error.REFUSED_STREAM, "Stream refused");
            }
            exchangeHandler = handler;
            context.setProtocolVersion(HttpVersion.HTTP_2);
            context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
            try {
                httpProcessor.process(request, requestEntityDetails, context);
                connMetrics.incrementRequestCount();
                receivedRequest = request;
                exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
            } catch (final HttpException ex) {
                if (!responseCommitted.get()) {
                    final AsyncResponseProducer responseProducer = new BasicResponseProducer(ServerSupport.toStatusCode(ex), ServerSupport.toErrorMessage(ex));
                    exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
                    exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
                } else {
                    throw ex;
                }
            }
            break;
        case BODY:
            responseState = MessageState.COMPLETE;
            exchangeHandler.streamEnd(headers);
            break;
        default:
            throw new ProtocolException("Unexpected message headers");
    }
}
Also used : HttpRequest(org.apache.hc.core5.http.HttpRequest) AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer) ProtocolException(org.apache.hc.core5.http.ProtocolException) EntityDetails(org.apache.hc.core5.http.EntityDetails) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails) H2StreamResetException(org.apache.hc.core5.http2.H2StreamResetException) IncomingEntityDetails(org.apache.hc.core5.http.impl.IncomingEntityDetails) HttpException(org.apache.hc.core5.http.HttpException) ImmediateResponseExchangeHandler(org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler) BasicResponseProducer(org.apache.hc.core5.http.nio.support.BasicResponseProducer) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

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