Search in sources :

Example 1 with AsyncClientExchangeHandler

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

the class ClientSessionEndpoint method execute.

public void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final HttpContext context) {
    Asserts.check(!closed.get(), "Connection is already closed");
    final Command executionCommand = new RequestExecutionCommand(exchangeHandler, pushHandlerFactory, null, context);
    ioSession.enqueue(executionCommand, Command.Priority.NORMAL);
    if (!ioSession.isOpen()) {
        exchangeHandler.failed(new ConnectionClosedException());
    }
}
Also used : ShutdownCommand(org.apache.hc.core5.http.nio.command.ShutdownCommand) Command(org.apache.hc.core5.reactor.Command) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand)

Example 2 with AsyncClientExchangeHandler

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

the class ClientH2StreamMultiplexer method createLocallyInitiatedStream.

@Override
H2StreamHandler createLocallyInitiatedStream(final ExecutableCommand command, final H2StreamChannel channel, final HttpProcessor httpProcessor, final BasicHttpConnectionMetrics connMetrics) throws IOException {
    if (command instanceof RequestExecutionCommand) {
        final RequestExecutionCommand executionCommand = (RequestExecutionCommand) command;
        final AsyncClientExchangeHandler exchangeHandler = executionCommand.getExchangeHandler();
        final HandlerFactory<AsyncPushConsumer> pushHandlerFactory = executionCommand.getPushHandlerFactory();
        final HttpCoreContext context = HttpCoreContext.adapt(executionCommand.getContext());
        context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
        return new ClientH2StreamHandler(channel, httpProcessor, connMetrics, exchangeHandler, pushHandlerFactory != null ? pushHandlerFactory : this.pushHandlerFactory, context);
    }
    throw new H2ConnectionException(H2Error.INTERNAL_ERROR, "Unexpected executable command");
}
Also used : AsyncPushConsumer(org.apache.hc.core5.http.nio.AsyncPushConsumer) AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) HttpCoreContext(org.apache.hc.core5.http.protocol.HttpCoreContext) H2ConnectionException(org.apache.hc.core5.http2.H2ConnectionException) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand)

Example 3 with AsyncClientExchangeHandler

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

the class H2MultiplexingRequester method execute.

private void execute(final AsyncClientExchangeHandler exchangeHandler, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final CancellableDependency cancellableDependency, final Timeout timeout, final HttpContext context) {
    Args.notNull(exchangeHandler, "Exchange handler");
    Args.notNull(timeout, "Timeout");
    Args.notNull(context, "Context");
    try {
        exchangeHandler.produceRequest((request, entityDetails, httpContext) -> {
            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);
            connPool.getSession(target, timeout, new FutureCallback<IOSession>() {

                @Override
                public void completed(final IOSession ioSession) {
                    ioSession.enqueue(new RequestExecutionCommand(new AsyncClientExchangeHandler() {

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

                        @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 {
                            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 {
                            exchangeHandler.streamEnd(trailers);
                        }

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

                        @Override
                        public void failed(final Exception cause) {
                            exchangeHandler.failed(cause);
                        }
                    }, pushHandlerFactory, cancellableDependency, context), Command.Priority.NORMAL);
                    if (!ioSession.isOpen()) {
                        exchangeHandler.failed(new ConnectionClosedException());
                    }
                }

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

                @Override
                public void cancelled() {
                    exchangeHandler.cancel();
                }
            });
        }, context);
    } 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) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpResponse(org.apache.hc.core5.http.HttpResponse) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) IOException(java.io.IOException) RequestExecutionCommand(org.apache.hc.core5.http.nio.command.RequestExecutionCommand) ByteBuffer(java.nio.ByteBuffer) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) 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) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) HttpHost(org.apache.hc.core5.http.HttpHost) EntityDetails(org.apache.hc.core5.http.EntityDetails) IOSession(org.apache.hc.core5.reactor.IOSession) HttpException(org.apache.hc.core5.http.HttpException) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel)

Example 4 with AsyncClientExchangeHandler

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

the class H2MultiplexingRequester method execute.

public final <T> Future<T> execute(final AsyncRequestProducer requestProducer, final AsyncResponseConsumer<T> responseConsumer, final HandlerFactory<AsyncPushConsumer> pushHandlerFactory, final Timeout timeout, final HttpContext context, final FutureCallback<T> callback) {
    Args.notNull(requestProducer, "Request producer");
    Args.notNull(responseConsumer, "Response consumer");
    Args.notNull(timeout, "Timeout");
    final ComplexFuture<T> future = new ComplexFuture<>(callback);
    final AsyncClientExchangeHandler exchangeHandler = new BasicClientExchangeHandler<>(requestProducer, responseConsumer, new FutureContribution<T>(future) {

        @Override
        public void completed(final T result) {
            future.completed(result);
        }
    });
    execute(exchangeHandler, pushHandlerFactory, future, timeout, context != null ? context : HttpCoreContext.create());
    return future;
}
Also used : AsyncClientExchangeHandler(org.apache.hc.core5.http.nio.AsyncClientExchangeHandler) BasicClientExchangeHandler(org.apache.hc.core5.http.nio.support.BasicClientExchangeHandler) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture)

Example 5 with AsyncClientExchangeHandler

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

the class H2FullDuplexClientExample 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
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).setMaxConcurrentStreams(100).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setIOReactorConfig(ioReactorConfig).setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).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://nghttp2.org/httpbin/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();
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : HttpConnection(org.apache.hc.core5.http.HttpConnection) 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) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) CapacityChannel(org.apache.hc.core5.http.nio.CapacityChannel) EntityDetails(org.apache.hc.core5.http.EntityDetails) BasicResponseConsumer(org.apache.hc.core5.http.nio.support.BasicResponseConsumer) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) 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) Header(org.apache.hc.core5.http.Header) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) RequestChannel(org.apache.hc.core5.http.nio.RequestChannel) H2Config(org.apache.hc.core5.http2.config.H2Config)

Aggregations

AsyncClientExchangeHandler (org.apache.hc.core5.http.nio.AsyncClientExchangeHandler)10 IOException (java.io.IOException)6 ByteBuffer (java.nio.ByteBuffer)6 EntityDetails (org.apache.hc.core5.http.EntityDetails)6 HttpException (org.apache.hc.core5.http.HttpException)6 HttpResponse (org.apache.hc.core5.http.HttpResponse)6 CapacityChannel (org.apache.hc.core5.http.nio.CapacityChannel)6 DataStreamChannel (org.apache.hc.core5.http.nio.DataStreamChannel)6 RequestChannel (org.apache.hc.core5.http.nio.RequestChannel)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 CountDownLatch (java.util.concurrent.CountDownLatch)4 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)4 BasicResponseConsumer (org.apache.hc.core5.http.nio.support.BasicResponseConsumer)4 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)4 List (java.util.List)3 ConnectionClosedException (org.apache.hc.core5.http.ConnectionClosedException)3 Header (org.apache.hc.core5.http.Header)3 StatusLine (org.apache.hc.core5.http.message.StatusLine)3 RequestExecutionCommand (org.apache.hc.core5.http.nio.command.RequestExecutionCommand)3 HttpCoreContext (org.apache.hc.core5.http.protocol.HttpCoreContext)3