Search in sources :

Example 21 with DataStreamChannel

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

the class AbstractServerExchangeHandler method produce.

@Override
public final void produce(final DataStreamChannel channel) throws IOException {
    final AsyncResponseProducer dataProducer = responseProducerRef.get();
    Asserts.notNull(dataProducer, "Data producer");
    dataProducer.produce(channel);
}
Also used : AsyncResponseProducer(org.apache.hc.core5.http.nio.AsyncResponseProducer)

Example 22 with DataStreamChannel

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

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

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

the class AsyncFullDuplexClientExample method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(5, TimeUnit.SECONDS).build();
    // Create and start requester
    // Disable 'Expect: Continue' handshake some servers cannot handle well
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setHttpProcessor(HttpProcessors.customClient(null).addLast((HttpRequestInterceptor) (request, entity, context) -> request.removeHeaders(HttpHeaders.EXPECT)).build()).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)");
            }
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final URI requestUri = new URI("http://httpbin.org/post");
    final AsyncRequestProducer requestProducer = AsyncRequestBuilder.post(requestUri).setEntity("stuff").build();
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    final CountDownLatch latch = new CountDownLatch(1);
    requester.execute(new AsyncClientExchangeHandler() {

        @Override
        public void releaseResources() {
            requestProducer.releaseResources();
            responseConsumer.releaseResources();
            latch.countDown();
        }

        @Override
        public void cancel() {
            System.out.println(requestUri + " cancelled");
        }

        @Override
        public void failed(final Exception cause) {
            System.out.println(requestUri + "->" + cause);
        }

        @Override
        public void produceRequest(final RequestChannel channel, final HttpContext httpContext) throws HttpException, IOException {
            requestProducer.sendRequest(channel, httpContext);
        }

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

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

        @Override
        public void consumeInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
            System.out.println(requestUri + "->" + response.getCode());
            responseConsumer.consumeResponse(response, entityDetails, httpContext, null);
        }

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

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

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            responseConsumer.streamEnd(trailers);
        }
    }, Timeout.ofSeconds(30), HttpCoreContext.create());
    latch.await(1, TimeUnit.MINUTES);
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) AsyncRequestBuilder(org.apache.hc.core5.http.nio.support.AsyncRequestBuilder) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) AsyncRequesterBootstrap(org.apache.hc.core5.http.impl.bootstrap.AsyncRequesterBootstrap) RequestLine(org.apache.hc.core5.http.message.RequestLine) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) ByteBuffer(java.nio.ByteBuffer) EntityDetails(org.apache.hc.core5.http.EntityDetails) StatusLine(org.apache.hc.core5.http.message.StatusLine) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpProcessors(org.apache.hc.core5.http.impl.HttpProcessors) CloseMode(org.apache.hc.core5.io.CloseMode) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) HttpResponse(org.apache.hc.core5.http.HttpResponse) URI(java.net.URI) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpException(org.apache.hc.core5.http.HttpException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) Header(org.apache.hc.core5.http.Header) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) IOException(java.io.IOException) Timeout(org.apache.hc.core5.util.Timeout) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHeaders(org.apache.hc.core5.http.HttpHeaders) List(java.util.List) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) HttpRequestInterceptor(org.apache.hc.core5.http.HttpRequestInterceptor) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) HttpConnection(org.apache.hc.core5.http.HttpConnection) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) URI(java.net.URI) AsyncRequestProducer(org.apache.hc.core5.http.nio.AsyncRequestProducer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) 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) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) 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) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 25 with DataStreamChannel

use of org.apache.hc.core5.http.nio.DataStreamChannel in project mercury by yellow013.

the class AsyncClientFullDuplexExchange method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final MinimalHttpAsyncClient client = HttpAsyncClients.createMinimal(HttpVersionPolicy.NEGOTIATE, H2Config.DEFAULT, Http1Config.DEFAULT, ioReactorConfig);
    client.start();
    final BasicHttpRequest request = BasicRequestBuilder.post("http://httpbin.org/post").build();
    final BasicRequestProducer requestProducer = new BasicRequestProducer(request, new BasicAsyncEntityProducer("stuff", ContentType.TEXT_PLAIN));
    final BasicResponseConsumer<String> responseConsumer = new BasicResponseConsumer<>(new StringAsyncEntityConsumer());
    System.out.println("Executing request " + request);
    final CountDownLatch latch = new CountDownLatch(1);
    client.execute(new AsyncClientExchangeHandler() {

        @Override
        public void releaseResources() {
            requestProducer.releaseResources();
            responseConsumer.releaseResources();
            latch.countDown();
        }

        @Override
        public void cancel() {
            System.out.println(request + " cancelled");
        }

        @Override
        public void failed(final Exception cause) {
            System.out.println(request + "->" + cause);
        }

        @Override
        public void produceRequest(final RequestChannel channel, final HttpContext context) throws HttpException, IOException {
            requestProducer.sendRequest(channel, context);
        }

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

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

        @Override
        public void consumeInformation(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
        }

        @Override
        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
            responseConsumer.consumeResponse(response, entityDetails, context, null);
        }

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

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

        @Override
        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
            responseConsumer.streamEnd(trailers);
        }
    });
    latch.await(1, TimeUnit.MINUTES);
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) MinimalHttpAsyncClient(org.apache.hc.client5.http.impl.async.MinimalHttpAsyncClient) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicAsyncEntityProducer(org.apache.hc.core5.http.nio.entity.BasicAsyncEntityProducer) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Aggregations

DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)37 Test (org.junit.jupiter.api.Test)23 ByteBuffer (java.nio.ByteBuffer)18 WritableByteChannelMock (org.apache.hc.core5.http.WritableByteChannelMock)18 AsyncEntityProducer (org.apache.hc.core5.http.nio.AsyncEntityProducer)18 IOException (java.io.IOException)15 HttpException (org.apache.hc.core5.http.HttpException)15 BasicDataStreamChannel (org.apache.hc.core5.http.nio.BasicDataStreamChannel)15 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)15 EntityDetails (org.apache.hc.core5.http.EntityDetails)14 HttpResponse (org.apache.hc.core5.http.HttpResponse)14 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)14 Header (org.apache.hc.core5.http.Header)10 HttpRequest (org.apache.hc.core5.http.HttpRequest)9 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)8 ResponseChannel (org.apache.hc.core5.http.nio.ResponseChannel)8 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)8 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)7 RequestChannel (org.apache.hc.core5.http.nio.RequestChannel)7 InetSocketAddress (java.net.InetSocketAddress)6