Search in sources :

Example 11 with AsyncResponseProducer

use of org.apache.hc.core5.http.nio.AsyncResponseProducer 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 12 with AsyncResponseProducer

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

the class BasicAsyncServerExpectationDecorator method releaseResources.

@Override
public final void releaseResources() {
    handler.releaseResources();
    final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
    if (dataProducer != null) {
        dataProducer.releaseResources();
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer)

Example 13 with AsyncResponseProducer

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

the class AbstractServerExchangeHandler method failed.

@Override
public final void failed(final Exception cause) {
    try {
        final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.get();
        if (requestConsumer != null) {
            requestConsumer.failed(cause);
        }
        final AsyncResponseProducer dataProducer = responseProducerRef.get();
        if (dataProducer != null) {
            dataProducer.failed(cause);
        }
    } finally {
        releaseResources();
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer)

Example 14 with AsyncResponseProducer

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

the class AbstractServerExchangeHandler method releaseResources.

@Override
public final void releaseResources() {
    final AsyncRequestConsumer<T> requestConsumer = requestConsumerRef.getAndSet(null);
    if (requestConsumer != null) {
        requestConsumer.releaseResources();
    }
    final AsyncResponseProducer dataProducer = responseProducerRef.getAndSet(null);
    if (dataProducer != null) {
        dataProducer.releaseResources();
    }
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer)

Example 15 with AsyncResponseProducer

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

AsyncResponseProducer (org.apache.hc.core5.http.nio.AsyncResponseProducer)15 BasicResponseProducer (org.apache.hc.core5.http.nio.support.BasicResponseProducer)9 HttpException (org.apache.hc.core5.http.HttpException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)8 Header (org.apache.hc.core5.http.Header)7 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)7 IOException (java.io.IOException)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 InterruptedIOException (java.io.InterruptedIOException)5 InetSocketAddress (java.net.InetSocketAddress)5 Message (org.apache.hc.core5.http.Message)5 ProtocolException (org.apache.hc.core5.http.ProtocolException)5 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)5 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)5 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)5 BasicRequestProducer (org.apache.hc.core5.http.nio.support.BasicRequestProducer)5 Test (org.junit.Test)5 EntityDetails (org.apache.hc.core5.http.EntityDetails)4 ImmediateResponseExchangeHandler (org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler)4