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;
}
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;
}
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;
}
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);
}
}
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());
}
Aggregations