Search in sources :

Example 11 with ResponseChannel

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

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

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

the class Http1IntegrationTest method testProtocolException.

@Test
public void testProtocolException() throws Exception {
    server.register("/boom", () -> new AsyncServerExchangeHandler() {

        private final StringAsyncEntityProducer entityProducer = new StringAsyncEntityProducer("Everyting is OK");

        @Override
        public void releaseResources() {
            entityProducer.releaseResources();
        }

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            final String requestUri = request.getRequestUri();
            if (requestUri.endsWith("boom")) {
                throw new ProtocolException("Boom!!!");
            }
            responseChannel.sendResponse(new BasicHttpResponse(200), entityProducer, 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 {
        // empty
        }

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

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

        @Override
        public void failed(final Exception cause) {
            releaseResources();
        }
    });
    final InetSocketAddress serverEndpoint = server.start();
    client.start();
    final Future<ClientSessionEndpoint> connectFuture = client.connect("localhost", serverEndpoint.getPort(), TIMEOUT);
    final ClientSessionEndpoint streamEndpoint = connectFuture.get();
    final Future<Message<HttpResponse, String>> future = streamEndpoint.execute(new BasicRequestProducer(Method.GET, createRequestURI(serverEndpoint, "/boom")), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
    final Message<HttpResponse, String> result = future.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
    Assertions.assertNotNull(result);
    final HttpResponse response1 = result.getHead();
    final String entity1 = result.getBody();
    Assertions.assertNotNull(response1);
    Assertions.assertEquals(HttpStatus.SC_BAD_REQUEST, response1.getCode());
    Assertions.assertEquals("Boom!!!", entity1);
}
Also used : Message(org.apache.hc.core5.http.Message) InetSocketAddress(java.net.InetSocketAddress) StringAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) 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) ProtocolException(org.apache.hc.core5.http.ProtocolException) 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) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Test(org.junit.Test)

Example 14 with ResponseChannel

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

the class AsyncFullDuplexServerExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).register("/echo", () -> new AsyncServerExchangeHandler() {

        ByteBuffer buffer = ByteBuffer.allocate(2048);

        CapacityChannel inputCapacityChannel;

        DataStreamChannel outputDataChannel;

        boolean endStream;

        private void ensureCapacity(final int chunk) {
            if (buffer.remaining() < chunk) {
                final ByteBuffer oldBuffer = buffer;
                oldBuffer.flip();
                buffer = ByteBuffer.allocate(oldBuffer.remaining() + (chunk > 2048 ? chunk : 2048));
                buffer.put(oldBuffer);
            }
        }

        @Override
        public void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
            final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
            responseChannel.sendResponse(response, entityDetails, context);
        }

        @Override
        public void consume(final ByteBuffer src) throws IOException {
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.write(src);
                }
            }
            if (src.hasRemaining()) {
                ensureCapacity(src.remaining());
                buffer.put(src);
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

        @Override
        public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
            if (buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
                inputCapacityChannel = null;
            } else {
                inputCapacityChannel = capacityChannel;
            }
        }

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws IOException {
            endStream = true;
            if (buffer.position() == 0) {
                if (outputDataChannel != null) {
                    outputDataChannel.endStream();
                }
            } else {
                if (outputDataChannel != null) {
                    outputDataChannel.requestOutput();
                }
            }
        }

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

        @Override
        public void produce(final DataStreamChannel channel) throws IOException {
            outputDataChannel = channel;
            buffer.flip();
            if (buffer.hasRemaining()) {
                channel.write(buffer);
            }
            buffer.compact();
            if (buffer.position() == 0 && endStream) {
                channel.endStream();
            }
            final CapacityChannel capacityChannel = inputCapacityChannel;
            if (capacityChannel != null && buffer.hasRemaining()) {
                capacityChannel.update(buffer.remaining());
            }
        }

        @Override
        public void failed(final Exception cause) {
            if (!(cause instanceof SocketException)) {
                cause.printStackTrace(System.out);
            }
        }

        @Override
        public void releaseResources() {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP server shutting down");
        server.close(CloseMode.GRACEFUL);
    }));
    server.start();
    final Future<ListenerEndpoint> future = server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    final ListenerEndpoint listenerEndpoint = future.get();
    System.out.print("Listening on " + listenerEndpoint.getAddress());
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) ByteBuffer(java.nio.ByteBuffer) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint) SocketException(java.net.SocketException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) ListenerEndpoint(org.apache.hc.core5.reactor.ListenerEndpoint)

Example 15 with ResponseChannel

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

the class AbstractClassicServerExchangeHandler method handleRequest.

@Override
public final void handleRequest(final HttpRequest request, final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException {
    final AtomicBoolean responseCommitted = new AtomicBoolean(false);
    final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK);
    final HttpResponse responseWrapper = new HttpResponseWrapper(response) {

        private void ensureNotCommitted() {
            Asserts.check(!responseCommitted.get(), "Response already committed");
        }

        @Override
        public void addHeader(final String name, final Object value) {
            ensureNotCommitted();
            super.addHeader(name, value);
        }

        @Override
        public void setHeader(final String name, final Object value) {
            ensureNotCommitted();
            super.setHeader(name, value);
        }

        @Override
        public void setVersion(final ProtocolVersion version) {
            ensureNotCommitted();
            super.setVersion(version);
        }

        @Override
        public void setCode(final int code) {
            ensureNotCommitted();
            super.setCode(code);
        }

        @Override
        public void setReasonPhrase(final String reason) {
            ensureNotCommitted();
            super.setReasonPhrase(reason);
        }

        @Override
        public void setLocale(final Locale locale) {
            ensureNotCommitted();
            super.setLocale(locale);
        }
    };
    final InputStream inputStream;
    if (entityDetails != null) {
        inputBuffer = new SharedInputBuffer(initialBufferSize);
        inputStream = new ContentInputStream(inputBuffer);
    } else {
        inputStream = null;
    }
    outputBuffer = new SharedOutputBuffer(initialBufferSize);
    final OutputStream outputStream = new ContentOutputStream(outputBuffer) {

        private void triggerResponse() throws IOException {
            try {
                if (responseCommitted.compareAndSet(false, true)) {
                    responseChannel.sendResponse(response, new EntityDetails() {

                        @Override
                        public long getContentLength() {
                            return -1;
                        }

                        @Override
                        public String getContentType() {
                            final Header h = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
                            return h != null ? h.getValue() : null;
                        }

                        @Override
                        public String getContentEncoding() {
                            final Header h = response.getFirstHeader(HttpHeaders.CONTENT_ENCODING);
                            return h != null ? h.getValue() : null;
                        }

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

                        @Override
                        public Set<String> getTrailerNames() {
                            return null;
                        }
                    }, context);
                }
            } catch (final HttpException ex) {
                throw new IOException(ex.getMessage(), ex);
            }
        }

        @Override
        public void close() throws IOException {
            triggerResponse();
            super.close();
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            triggerResponse();
            super.write(b, off, len);
        }

        @Override
        public void write(final byte[] b) throws IOException {
            triggerResponse();
            super.write(b);
        }

        @Override
        public void write(final int b) throws IOException {
            triggerResponse();
            super.write(b);
        }
    };
    if (state.compareAndSet(State.IDLE, State.ACTIVE)) {
        executor.execute(() -> {
            try {
                handle(request, inputStream, responseWrapper, outputStream, context);
                Closer.close(inputStream);
                outputStream.close();
            } catch (final Exception ex) {
                exception.compareAndSet(null, ex);
                if (inputBuffer != null) {
                    inputBuffer.abort();
                }
                outputBuffer.abort();
            } finally {
                state.set(State.COMPLETED);
            }
        });
    }
}
Also used : Locale(java.util.Locale) HttpResponseWrapper(org.apache.hc.core5.http.message.HttpResponseWrapper) Set(java.util.Set) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) IOException(java.io.IOException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) Header(org.apache.hc.core5.http.Header) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException)

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