Search in sources :

Example 11 with AsyncPushConsumer

use of org.apache.hc.core5.http.nio.AsyncPushConsumer in project httpcomponents-client by apache.

the class MinimalHttpAsyncClient method execute.

@Override
public Cancellable execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final HttpContext context) {
    final ComplexCancellable cancellable = new ComplexCancellable();
    try {
        if (!isRunning()) {
            throw new CancellationException("Request execution cancelled");
        }
        final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
        exchangeHandler.produceRequest((request, entityDetails, context1) -> {
            RequestConfig requestConfig = null;
            if (request instanceof Configurable) {
                requestConfig = ((Configurable) request).getConfig();
            }
            if (requestConfig != null) {
                clientContext.setRequestConfig(requestConfig);
            } else {
                requestConfig = clientContext.getRequestConfig();
            }
            final Timeout connectionRequestTimeout = requestConfig.getConnectionRequestTimeout();
            @SuppressWarnings("deprecation") final Timeout connectTimeout = requestConfig.getConnectTimeout();
            final Timeout responseTimeout = requestConfig.getResponseTimeout();
            final HttpHost target = new HttpHost(request.getScheme(), request.getAuthority());
            final Future<AsyncConnectionEndpoint> leaseFuture = leaseEndpoint(target, connectionRequestTimeout, connectTimeout, clientContext, new FutureCallback<AsyncConnectionEndpoint>() {

                @Override
                public void completed(final AsyncConnectionEndpoint connectionEndpoint) {
                    final InternalAsyncClientEndpoint endpoint = new InternalAsyncClientEndpoint(connectionEndpoint);
                    final AtomicInteger messageCountDown = new AtomicInteger(2);
                    final AsyncClientExchangeHandler internalExchangeHandler = new AsyncClientExchangeHandler() {

                        @Override
                        public void releaseResources() {
                            try {
                                exchangeHandler.releaseResources();
                            } finally {
                                endpoint.releaseAndDiscard();
                            }
                        }

                        @Override
                        public void failed(final Exception cause) {
                            try {
                                exchangeHandler.failed(cause);
                            } finally {
                                endpoint.releaseAndDiscard();
                            }
                        }

                        @Override
                        public void cancel() {
                            failed(new RequestFailedException("Request aborted"));
                        }

                        @Override
                        public void produceRequest(final RequestChannel channel, final HttpContext context1) throws HttpException, IOException {
                            channel.sendRequest(request, entityDetails, context1);
                            if (entityDetails == null) {
                                messageCountDown.decrementAndGet();
                            }
                        }

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

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

                                @Override
                                public void requestOutput() {
                                    channel.requestOutput();
                                }

                                @Override
                                public int write(final ByteBuffer src) throws IOException {
                                    return channel.write(src);
                                }

                                @Override
                                public void endStream(final List<? extends Header> trailers) throws IOException {
                                    channel.endStream(trailers);
                                    if (messageCountDown.decrementAndGet() <= 0) {
                                        endpoint.releaseAndReuse();
                                    }
                                }

                                @Override
                                public void endStream() throws IOException {
                                    channel.endStream();
                                    if (messageCountDown.decrementAndGet() <= 0) {
                                        endpoint.releaseAndReuse();
                                    }
                                }
                            });
                        }

                        @Override
                        public void consumeInformation(final HttpResponse response, final HttpContext context1) throws HttpException, IOException {
                            exchangeHandler.consumeInformation(response, context1);
                        }

                        @Override
                        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext context1) throws HttpException, IOException {
                            exchangeHandler.consumeResponse(response, entityDetails, context1);
                            if (response.getCode() >= HttpStatus.SC_CLIENT_ERROR) {
                                messageCountDown.decrementAndGet();
                            }
                            if (entityDetails == null) {
                                if (messageCountDown.decrementAndGet() <= 0) {
                                    endpoint.releaseAndReuse();
                                }
                            }
                        }

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

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

                        @Override
                        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                            if (messageCountDown.decrementAndGet() <= 0) {
                                endpoint.releaseAndReuse();
                            }
                            exchangeHandler.streamEnd(trailers);
                        }
                    };
                    if (responseTimeout != null) {
                        endpoint.setSocketTimeout(responseTimeout);
                    }
                    endpoint.execute(internalExchangeHandler, pushHandlerFactory, clientContext);
                }

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

                @Override
                public void cancelled() {
                    exchangeHandler.cancel();
                }
            });
            cancellable.setDependency(() -> leaseFuture.cancel(true));
        }, context);
    } catch (final HttpException | IOException | IllegalStateException ex) {
        exchangeHandler.failed(ex);
    }
    return cancellable;
}
Also used : AsyncConnectionEndpoint(org.apache.hc.client5.http.nio.AsyncConnectionEndpoint) Configurable(org.apache.hc.client5.http.config.Configurable) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) HttpHost(org.apache.hc.core5.http.HttpHost) EntityDetails(org.apache.hc.core5.http.EntityDetails) HttpException(org.apache.hc.core5.http.HttpException) List(java.util.List) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) Timeout(org.apache.hc.core5.util.Timeout) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) RequestFailedException(org.apache.hc.client5.http.impl.classic.RequestFailedException) CancellationException(java.util.concurrent.CancellationException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) Header(org.apache.hc.core5.http.Header) CancellationException(java.util.concurrent.CancellationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RequestFailedException(org.apache.hc.client5.http.impl.classic.RequestFailedException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) ComplexCancellable(org.apache.hc.core5.concurrent.ComplexCancellable)

Example 12 with AsyncPushConsumer

use of org.apache.hc.core5.http.nio.AsyncPushConsumer in project httpcomponents-client by apache.

the class InternalAbstractHttpAsyncClient method doExecute.

@Override
protected <T> Future<T> doExecute(final HttpHost httpHost, final AsyncRequestProducer requestProducer, final AsyncResponseConsumer<T> responseConsumer, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final HttpContext context, final FutureCallback<T> callback) {
    final ComplexFuture<T> future = new ComplexFuture<>(callback);
    try {
        if (!isRunning()) {
            throw new CancellationException("Request execution cancelled");
        }
        final HttpClientContext clientContext = context != null ? HttpClientContext.adapt(context) : HttpClientContext.create();
        requestProducer.sendRequest((request, entityDetails, c) -> {
            RequestConfig requestConfig = null;
            if (request instanceof Configurable) {
                requestConfig = ((Configurable) request).getConfig();
            }
            if (requestConfig != null) {
                clientContext.setRequestConfig(requestConfig);
            }
            final HttpRoute route = determineRoute(httpHost != null ? httpHost : RoutingSupport.determineHost(request), clientContext);
            final String exchangeId = ExecSupport.getNextExchangeId();
            clientContext.setExchangeId(exchangeId);
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} preparing request execution", exchangeId);
            }
            final AsyncExecRuntime execRuntime = createAsyncExecRuntime(pushHandlerFactory);
            setupContext(clientContext);
            final AsyncExecChain.Scheduler scheduler = this::executeScheduled;
            final AsyncExecChain.Scope scope = new AsyncExecChain.Scope(exchangeId, route, request, future, clientContext, execRuntime, scheduler, new AtomicInteger(1));
            final AtomicBoolean outputTerminated = new AtomicBoolean(false);
            executeImmediate(BasicRequestBuilder.copy(request).build(), entityDetails != null ? new AsyncEntityProducer() {

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

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

                @Override
                public boolean isRepeatable() {
                    return requestProducer.isRepeatable();
                }

                @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 requestProducer.available();
                }

                @Override
                public void produce(final DataStreamChannel channel) throws IOException {
                    if (outputTerminated.get()) {
                        channel.endStream();
                        return;
                    }
                    requestProducer.produce(channel);
                }
            } : null, scope, new AsyncExecCallback() {

                @Override
                public AsyncDataConsumer handleResponse(final HttpResponse response, final EntityDetails entityDetails) throws HttpException, IOException {
                    if (response.getCode() >= HttpStatus.SC_CLIENT_ERROR) {
                        outputTerminated.set(true);
                        requestProducer.releaseResources();
                    }
                    responseConsumer.consumeResponse(response, entityDetails, c, new FutureCallback<T>() {

                        @Override
                        public void completed(final T result) {
                            future.completed(result);
                        }

                        @Override
                        public void failed(final Exception ex) {
                            future.failed(ex);
                        }

                        @Override
                        public void cancelled() {
                            future.cancel();
                        }
                    });
                    return entityDetails != null ? responseConsumer : null;
                }

                @Override
                public void handleInformationResponse(final HttpResponse response) throws HttpException, IOException {
                    responseConsumer.informationResponse(response, c);
                }

                @Override
                public void completed() {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{} message exchange successfully completed", exchangeId);
                    }
                    try {
                        execRuntime.releaseEndpoint();
                    } finally {
                        responseConsumer.releaseResources();
                        requestProducer.releaseResources();
                    }
                }

                @Override
                public void failed(final Exception cause) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{} request failed: {}", exchangeId, cause.getMessage());
                    }
                    try {
                        execRuntime.discardEndpoint();
                        responseConsumer.failed(cause);
                    } finally {
                        try {
                            future.failed(cause);
                        } finally {
                            responseConsumer.releaseResources();
                            requestProducer.releaseResources();
                        }
                    }
                }
            });
        }, context);
    } catch (final HttpException | IOException | IllegalStateException ex) {
        future.failed(ex);
    }
    return future;
}
Also used : AsyncExecCallback(org.apache.hc.client5.http.async.AsyncExecCallback) AsyncExecChain(org.apache.hc.client5.http.async.AsyncExecChain) Configurable(org.apache.hc.client5.http.config.Configurable) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) AsyncDataConsumer(org.apache.hc.core5.http.nio.AsyncDataConsumer) HttpException(org.apache.hc.core5.http.HttpException) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpResponse(org.apache.hc.core5.http.HttpResponse) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) IOException(java.io.IOException) CancellationException(java.util.concurrent.CancellationException) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) HttpRoute(org.apache.hc.client5.http.HttpRoute) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsyncEntityProducer(org.apache.hc.core5.http.nio.AsyncEntityProducer) CancellationException(java.util.concurrent.CancellationException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncExecRuntime(org.apache.hc.client5.http.async.AsyncExecRuntime) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture)

Example 13 with AsyncPushConsumer

use of org.apache.hc.core5.http.nio.AsyncPushConsumer in project httpcomponents-client by apache.

the class AsyncPushConsumerRegistry method get.

public AsyncPushConsumer get(final HttpRequest request) {
    Args.notNull(request, "Request");
    final URIAuthority authority = request.getAuthority();
    final String key = authority != null ? authority.getHostName().toLowerCase(Locale.ROOT) : null;
    final UriPatternMatcher<Supplier<AsyncPushConsumer>> patternMatcher = getPatternMatcher(key);
    if (patternMatcher == null) {
        return null;
    }
    String path = request.getPath();
    final int i = path.indexOf('?');
    if (i != -1) {
        path = path.substring(0, i);
    }
    final Supplier<AsyncPushConsumer> supplier = patternMatcher.lookup(path);
    return supplier != null ? supplier.get() : null;
}
Also used : AsyncPushConsumer(org.apache.hc.core5.http.nio.AsyncPushConsumer) URIAuthority(org.apache.hc.core5.net.URIAuthority) Supplier(org.apache.hc.core5.function.Supplier)

Example 14 with AsyncPushConsumer

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

the class HttpAsyncRequester method execute.

public void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext executeContext) {
    Args.notNull(exchangeHandler, "Exchange handler");
    Args.notNull(timeout, "Timeout");
    Args.notNull(executeContext, "Context");
    try {
        exchangeHandler.produceRequest((request, entityDetails, requestContext) -> {
            final String scheme = request.getScheme();
            final URIAuthority authority = request.getAuthority();
            if (authority == null) {
                throw new ProtocolException("Request authority not specified");
            }
            final HttpHost target = new HttpHost(scheme, authority);
            connect(target, timeout, null, new FutureCallback<AsyncClientEndpoint>() {

                @Override
                public void completed(final AsyncClientEndpoint endpoint) {
                    endpoint.execute(new AsyncClientExchangeHandler() {

                        @Override
                        public void releaseResources() {
                            endpoint.releaseAndDiscard();
                            exchangeHandler.releaseResources();
                        }

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

                        @Override
                        public void cancel() {
                            endpoint.releaseAndDiscard();
                            exchangeHandler.cancel();
                        }

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

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

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

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

                        @Override
                        public void consumeResponse(final HttpResponse response, final EntityDetails entityDetails, final HttpContext httpContext) throws HttpException, IOException {
                            if (entityDetails == null) {
                                endpoint.releaseAndReuse();
                            }
                            exchangeHandler.consumeResponse(response, entityDetails, httpContext);
                        }

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

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

                        @Override
                        public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
                            endpoint.releaseAndReuse();
                            exchangeHandler.streamEnd(trailers);
                        }
                    }, pushHandlerFactory, executeContext);
                }

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

                @Override
                public void cancelled() {
                    exchangeHandler.cancel();
                }
            });
        }, executeContext);
    } catch (final IOException | HttpException ex) {
        exchangeHandler.failed(ex);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) ProtocolException(org.apache.hc.core5.http.ProtocolException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) EntityDetails(org.apache.hc.core5.http.EntityDetails) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 15 with AsyncPushConsumer

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

the class H2MultiplexingRequesterBootstrap method create.

public H2MultiplexingRequester create() {
    final RequestHandlerRegistry<Supplier<AsyncPushConsumer>> registry = new RequestHandlerRegistry<>(uriPatternType);
    for (final HandlerEntry<Supplier<AsyncPushConsumer>> entry : pushConsumerList) {
        registry.register(entry.hostname, entry.uriPattern, entry.handler);
    }
    final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.client(), new DefaultAsyncPushConsumerFactory(registry), h2Config != null ? h2Config : H2Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, streamListener);
    return new H2MultiplexingRequester(ioReactorConfig, (ioSession, attachment) -> new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, strictALPNHandshake), ioSessionDecorator, exceptionCallback, sessionListener, DefaultAddressResolver.INSTANCE, tlsStrategy != null ? tlsStrategy : new H2ClientTlsStrategy());
}
Also used : RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) DefaultAsyncPushConsumerFactory(org.apache.hc.core5.http2.nio.support.DefaultAsyncPushConsumerFactory) ClientH2PrefaceHandler(org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler) ClientH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory) H2ClientTlsStrategy(org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy) Supplier(org.apache.hc.core5.function.Supplier)

Aggregations

AsyncClientExchangeHandler (org.apache.hc.core5.http.nio.AsyncClientExchangeHandler)7 IOException (java.io.IOException)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpResponse (org.apache.hc.core5.http.HttpResponse)6 ByteBuffer (java.nio.ByteBuffer)5 EntityDetails (org.apache.hc.core5.http.EntityDetails)5 HttpHost (org.apache.hc.core5.http.HttpHost)5 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)5 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)4 RequestChannel (org.apache.hc.core5.http.nio.RequestChannel)4 RequestExecutionCommand (org.apache.hc.core5.http.nio.command.RequestExecutionCommand)4 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)4 CancellationException (java.util.concurrent.CancellationException)3 Configurable (org.apache.hc.client5.http.config.Configurable)3 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)3 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)3 Supplier (org.apache.hc.core5.function.Supplier)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 AsyncPushConsumer (org.apache.hc.core5.http.nio.AsyncPushConsumer)3 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)3