Search in sources :

Example 6 with H2Config

use of org.apache.hc.core5.http2.config.H2Config 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)

Example 7 with H2Config

use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.

the class H2FullDuplexServerExample 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 H2Config h2Config = H2Config.custom().setPushEnabled(true).setMaxConcurrentStreams(100).build();
    final HttpAsyncServer server = H2ServerBootstrap.bootstrap().setIOReactorConfig(config).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) {
        }
    }).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.ofDays(Long.MAX_VALUE));
}
Also used : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) 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) 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) 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) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) H2Config(org.apache.hc.core5.http2.config.H2Config)

Example 8 with H2Config

use of org.apache.hc.core5.http2.config.H2Config in project mercury by yellow013.

the class AsyncClientH2ServerPush method main.

public static void main(final String[] args) throws Exception {
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(Timeout.ofSeconds(5)).build();
    final H2Config h2Config = H2Config.custom().setPushEnabled(true).build();
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setIOReactorConfig(ioReactorConfig).setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2).setH2Config(h2Config).build();
    client.start();
    client.register("*", new Supplier<AsyncPushConsumer>() {

        @Override
        public AsyncPushConsumer get() {
            return new AbstractBinPushConsumer() {

                @Override
                protected void start(final HttpRequest promise, final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
                    System.out.println(promise.getPath() + " (push)->" + new StatusLine(response));
                }

                @Override
                protected int capacityIncrement() {
                    return Integer.MAX_VALUE;
                }

                @Override
                protected void data(final ByteBuffer data, final boolean endOfStream) throws IOException {
                }

                @Override
                protected void completed() {
                }

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

                @Override
                public void releaseResources() {
                }
            };
        }
    });
    final BasicHttpRequest request = BasicRequestBuilder.get("https://nghttp2.org/httpbin/").build();
    System.out.println("Executing request " + request);
    final Future<Void> future = client.execute(new BasicRequestProducer(request, null), new AbstractCharResponseConsumer<Void>() {

        @Override
        protected void start(final HttpResponse response, final ContentType contentType) throws HttpException, IOException {
            System.out.println(request + "->" + new StatusLine(response));
        }

        @Override
        protected int capacityIncrement() {
            return Integer.MAX_VALUE;
        }

        @Override
        protected void data(final CharBuffer data, final boolean endOfStream) throws IOException {
        }

        @Override
        protected Void buildResult() throws IOException {
            return null;
        }

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

        @Override
        public void releaseResources() {
        }
    }, null);
    future.get();
    System.out.println("Shutting down");
    client.close(CloseMode.GRACEFUL);
}
Also used : AsyncPushConsumer(org.apache.hc.core5.http.nio.AsyncPushConsumer) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) AbstractBinPushConsumer(org.apache.hc.client5.http.async.methods.AbstractBinPushConsumer) ContentType(org.apache.hc.core5.http.ContentType) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) CharBuffer(java.nio.CharBuffer) HttpResponse(org.apache.hc.core5.http.HttpResponse) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) HttpException(org.apache.hc.core5.http.HttpException) IOException(java.io.IOException) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) StatusLine(org.apache.hc.core5.http.message.StatusLine) CloseableHttpAsyncClient(org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient) HttpException(org.apache.hc.core5.http.HttpException) H2Config(org.apache.hc.core5.http2.config.H2Config)

Example 9 with H2Config

use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.

the class InternalClientProtocolNegotiationStarter method createHandler.

@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
    if (sslContext != null) {
        ioSession.startTls(sslContext, null, null, sslSessionInitializer, sslSessionVerifier, null);
    }
    final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ClientHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.client(), http1Config, charCodingConfig, LoggingHttp1StreamListener.INSTANCE_CLIENT);
    final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.client(), exchangeHandlerFactory, h2Config, charCodingConfig, LoggingH2StreamListener.INSTANCE);
    ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ClientHttp1UpgradeHandler(http1StreamHandlerFactory));
    ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ClientH2UpgradeHandler(http2StreamHandlerFactory));
    switch(versionPolicy) {
        case FORCE_HTTP_2:
            return new ClientH2PrefaceHandler(ioSession, http2StreamHandlerFactory, false);
        case FORCE_HTTP_1:
            return new ClientHttp1IOEventHandler(http1StreamHandlerFactory.create(ioSession));
        default:
            return new HttpProtocolNegotiator(ioSession, null);
    }
}
Also used : ClientH2PrefaceHandler(org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler) ClientHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory) HttpProtocolNegotiator(org.apache.hc.core5.http2.impl.nio.HttpProtocolNegotiator) ClientH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory) ClientH2UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ClientH2UpgradeHandler) ClientHttp1UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ClientHttp1UpgradeHandler) ClientHttp1IOEventHandler(org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandler)

Example 10 with H2Config

use of org.apache.hc.core5.http2.config.H2Config in project httpcomponents-core by apache.

the class InternalServerProtocolNegotiationStarter method createHandler.

@Override
public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
    if (sslContext != null) {
        ioSession.startTls(sslContext, null, null, sslSessionInitializer, sslSessionVerifier, null);
    }
    final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ServerHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.server(), exchangeHandlerFactory, http1Config, charCodingConfig, LoggingHttp1StreamListener.INSTANCE_SERVER);
    final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory = new ServerH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.server(), exchangeHandlerFactory, h2Config, charCodingConfig, LoggingH2StreamListener.INSTANCE);
    ioSession.registerProtocol(ApplicationProtocol.HTTP_1_1.id, new ServerHttp1UpgradeHandler(http1StreamHandlerFactory));
    ioSession.registerProtocol(ApplicationProtocol.HTTP_2.id, new ServerH2UpgradeHandler(http2StreamHandlerFactory));
    switch(versionPolicy) {
        case FORCE_HTTP_2:
            return new ServerH2PrefaceHandler(ioSession, http2StreamHandlerFactory);
        case FORCE_HTTP_1:
            return new ServerHttp1IOEventHandler(http1StreamHandlerFactory.create(sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id, ioSession));
        default:
            return new HttpProtocolNegotiator(ioSession, null);
    }
}
Also used : ServerHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory) ServerH2PrefaceHandler(org.apache.hc.core5.http2.impl.nio.ServerH2PrefaceHandler) HttpProtocolNegotiator(org.apache.hc.core5.http2.impl.nio.HttpProtocolNegotiator) ServerH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ServerH2StreamMultiplexerFactory) ServerHttp1IOEventHandler(org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandler) ServerHttp1UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ServerHttp1UpgradeHandler) ServerH2UpgradeHandler(org.apache.hc.core5.http2.impl.nio.ServerH2UpgradeHandler)

Aggregations

H2Config (org.apache.hc.core5.http2.config.H2Config)9 List (java.util.List)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)8 H2StreamListener (org.apache.hc.core5.http2.impl.nio.H2StreamListener)8 Header (org.apache.hc.core5.http.Header)7 HttpConnection (org.apache.hc.core5.http.HttpConnection)7 RawFrame (org.apache.hc.core5.http2.frame.RawFrame)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 HttpHost (org.apache.hc.core5.http.HttpHost)6 HttpAsyncRequester (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)6 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)6 Message (org.apache.hc.core5.http.Message)5 AsyncClientEndpoint (org.apache.hc.core5.http.nio.AsyncClientEndpoint)5 HttpException (org.apache.hc.core5.http.HttpException)4 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)4 IOException (java.io.IOException)3 ByteBuffer (java.nio.ByteBuffer)3 Supplier (org.apache.hc.core5.function.Supplier)3 HttpRequest (org.apache.hc.core5.http.HttpRequest)3 RequestHandlerRegistry (org.apache.hc.core5.http.protocol.RequestHandlerRegistry)3