Search in sources :

Example 1 with HttpAsyncServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer in project httpcomponents-core by apache.

the class H2ServerBootstrap method create.

public HttpAsyncServer create() {
    final String actualCanonicalHostName = canonicalHostName != null ? canonicalHostName : InetAddressUtils.getCanonicalLocalHostName();
    final RequestHandlerRegistry<Supplier<AsyncServerExchangeHandler>> registry = new RequestHandlerRegistry<>(actualCanonicalHostName, () -> lookupRegistry != null ? lookupRegistry : UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
    for (final HandlerEntry<Supplier<AsyncServerExchangeHandler>> entry : handlerList) {
        registry.register(entry.hostname, entry.uriPattern, entry.handler);
    }
    final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
    if (!filters.isEmpty()) {
        final NamedElementChain<AsyncFilterHandler> filterChainDefinition = new NamedElementChain<>();
        filterChainDefinition.addLast(new TerminalAsyncServerFilter(new DefaultAsyncResponseExchangeHandlerFactory(registry)), StandardFilter.MAIN_HANDLER.name());
        filterChainDefinition.addFirst(new AsyncServerExpectationFilter(), StandardFilter.EXPECT_CONTINUE.name());
        for (final FilterEntry<AsyncFilterHandler> entry : filters) {
            switch(entry.position) {
                case AFTER:
                    filterChainDefinition.addAfter(entry.existing, entry.filterHandler, entry.name);
                    break;
                case BEFORE:
                    filterChainDefinition.addBefore(entry.existing, entry.filterHandler, entry.name);
                    break;
                case REPLACE:
                    filterChainDefinition.replace(entry.existing, entry.filterHandler);
                    break;
                case FIRST:
                    filterChainDefinition.addFirst(entry.filterHandler, entry.name);
                    break;
                case LAST:
                    // Don't add last, after TerminalAsyncServerFilter, as that does not delegate to the chain
                    // Instead, add the filter just before it, making it effectively the last filter
                    filterChainDefinition.addBefore(StandardFilter.MAIN_HANDLER.name(), entry.filterHandler, entry.name);
                    break;
            }
        }
        NamedElementChain<AsyncFilterHandler>.Node current = filterChainDefinition.getLast();
        AsyncServerFilterChainElement execChain = null;
        while (current != null) {
            execChain = new AsyncServerFilterChainElement(current.getValue(), execChain);
            current = current.getPrevious();
        }
        handlerFactory = new AsyncServerFilterChainExchangeHandlerFactory(execChain, exceptionCallback);
    } else {
        handlerFactory = new DefaultAsyncResponseExchangeHandlerFactory(registry, handler -> new BasicAsyncServerExpectationDecorator(handler, exceptionCallback));
    }
    final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory = new ServerH2StreamMultiplexerFactory(httpProcessor != null ? httpProcessor : H2Processors.server(), handlerFactory, h2Config != null ? h2Config : H2Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, h2StreamListener);
    final TlsStrategy actualTlsStrategy = tlsStrategy != null ? tlsStrategy : new H2ServerTlsStrategy();
    final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory = new ServerHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.server(), handlerFactory, http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, DefaultConnectionReuseStrategy.INSTANCE, DefaultHttpRequestParserFactory.INSTANCE, DefaultHttpResponseWriterFactory.INSTANCE, DefaultContentLengthStrategy.INSTANCE, DefaultContentLengthStrategy.INSTANCE, http1StreamListener);
    final IOEventHandlerFactory ioEventHandlerFactory = new ServerHttpProtocolNegotiationStarter(http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE, actualTlsStrategy, handshakeTimeout);
    return new HttpAsyncServer(ioEventHandlerFactory, ioReactorConfig, ioSessionDecorator, exceptionCallback, sessionListener, actualCanonicalHostName);
}
Also used : AsyncServerFilterChainElement(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainElement) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) AsyncServerFilterChainExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainExchangeHandlerFactory) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) Args(org.apache.hc.core5.util.Args) H2Config(org.apache.hc.core5.http2.config.H2Config) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) AsyncServerFilterChainElement(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainElement) BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) IOSessionListener(org.apache.hc.core5.reactor.IOSessionListener) Supplier(org.apache.hc.core5.function.Supplier) ArrayList(java.util.ArrayList) HttpVersionPolicy(org.apache.hc.core5.http2.HttpVersionPolicy) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpProcessors(org.apache.hc.core5.http.impl.HttpProcessors) DefaultHttpResponseWriterFactory(org.apache.hc.core5.http.impl.nio.DefaultHttpResponseWriterFactory) LookupRegistry(org.apache.hc.core5.http.protocol.LookupRegistry) Http1Config(org.apache.hc.core5.http.config.Http1Config) NamedElementChain(org.apache.hc.core5.http.config.NamedElementChain) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) AsyncFilterHandler(org.apache.hc.core5.http.nio.AsyncFilterHandler) ServerHttpProtocolNegotiationStarter(org.apache.hc.core5.http2.impl.nio.ServerHttpProtocolNegotiationStarter) BasicServerExchangeHandler(org.apache.hc.core5.http.nio.support.BasicServerExchangeHandler) Decorator(org.apache.hc.core5.function.Decorator) HandlerFactory(org.apache.hc.core5.http.nio.HandlerFactory) Callback(org.apache.hc.core5.function.Callback) Timeout(org.apache.hc.core5.util.Timeout) H2Processors(org.apache.hc.core5.http2.impl.H2Processors) DefaultContentLengthStrategy(org.apache.hc.core5.http.impl.DefaultContentLengthStrategy) UriPatternType(org.apache.hc.core5.http.protocol.UriPatternType) H2ServerTlsStrategy(org.apache.hc.core5.http2.ssl.H2ServerTlsStrategy) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory) List(java.util.List) ServerH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ServerH2StreamMultiplexerFactory) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) DefaultHttpRequestParserFactory(org.apache.hc.core5.http.impl.nio.DefaultHttpRequestParserFactory) IOSession(org.apache.hc.core5.reactor.IOSession) TerminalAsyncServerFilter(org.apache.hc.core5.http.nio.support.TerminalAsyncServerFilter) InetAddressUtils(org.apache.hc.core5.net.InetAddressUtils) ServerHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory) TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) AsyncServerExpectationFilter(org.apache.hc.core5.http.nio.support.AsyncServerExpectationFilter) DefaultAsyncResponseExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.DefaultAsyncResponseExchangeHandlerFactory) DefaultConnectionReuseStrategy(org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy) StandardFilter(org.apache.hc.core5.http.impl.bootstrap.StandardFilter) H2ServerTlsStrategy(org.apache.hc.core5.http2.ssl.H2ServerTlsStrategy) TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) ServerHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory) BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) AsyncServerExpectationFilter(org.apache.hc.core5.http.nio.support.AsyncServerExpectationFilter) DefaultAsyncResponseExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.DefaultAsyncResponseExchangeHandlerFactory) Supplier(org.apache.hc.core5.function.Supplier) ServerH2StreamMultiplexerFactory(org.apache.hc.core5.http2.impl.nio.ServerH2StreamMultiplexerFactory) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) AsyncFilterHandler(org.apache.hc.core5.http.nio.AsyncFilterHandler) TerminalAsyncServerFilter(org.apache.hc.core5.http.nio.support.TerminalAsyncServerFilter) NamedElementChain(org.apache.hc.core5.http.config.NamedElementChain) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) H2ServerTlsStrategy(org.apache.hc.core5.http2.ssl.H2ServerTlsStrategy) ServerHttpProtocolNegotiationStarter(org.apache.hc.core5.http2.impl.nio.ServerHttpProtocolNegotiationStarter) AsyncServerFilterChainExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainExchangeHandlerFactory) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory)

Example 2 with HttpAsyncServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer 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 3 with HttpAsyncServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer in project httpcomponents-core by apache.

the class AsyncServerBootstrap method create.

public HttpAsyncServer create() {
    final RequestHandlerRegistry<Supplier<AsyncServerExchangeHandler>> registry = new RequestHandlerRegistry<>(canonicalHostName != null ? canonicalHostName : InetAddressUtils.getCanonicalLocalHostName(), () -> lookupRegistry != null ? lookupRegistry : UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
    for (final HandlerEntry<Supplier<AsyncServerExchangeHandler>> entry : handlerList) {
        registry.register(entry.hostname, entry.uriPattern, entry.handler);
    }
    final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
    if (!filters.isEmpty()) {
        final NamedElementChain<AsyncFilterHandler> filterChainDefinition = new NamedElementChain<>();
        filterChainDefinition.addLast(new TerminalAsyncServerFilter(new DefaultAsyncResponseExchangeHandlerFactory(registry)), StandardFilter.MAIN_HANDLER.name());
        filterChainDefinition.addFirst(new AsyncServerExpectationFilter(), StandardFilter.EXPECT_CONTINUE.name());
        for (final FilterEntry<AsyncFilterHandler> entry : filters) {
            switch(entry.position) {
                case AFTER:
                    filterChainDefinition.addAfter(entry.existing, entry.filterHandler, entry.name);
                    break;
                case BEFORE:
                    filterChainDefinition.addBefore(entry.existing, entry.filterHandler, entry.name);
                    break;
                case REPLACE:
                    filterChainDefinition.replace(entry.existing, entry.filterHandler);
                    break;
                case FIRST:
                    filterChainDefinition.addFirst(entry.filterHandler, entry.name);
                    break;
                case LAST:
                    // Don't add last, after TerminalAsyncServerFilter, as that does not delegate to the chain
                    // Instead, add the filter just before it, making it effectively the last filter
                    filterChainDefinition.addBefore(StandardFilter.MAIN_HANDLER.name(), entry.filterHandler, entry.name);
                    break;
            }
        }
        NamedElementChain<AsyncFilterHandler>.Node current = filterChainDefinition.getLast();
        AsyncServerFilterChainElement execChain = null;
        while (current != null) {
            execChain = new AsyncServerFilterChainElement(current.getValue(), execChain);
            current = current.getPrevious();
        }
        handlerFactory = new AsyncServerFilterChainExchangeHandlerFactory(execChain, exceptionCallback);
    } else {
        handlerFactory = new DefaultAsyncResponseExchangeHandlerFactory(registry, handler -> new BasicAsyncServerExpectationDecorator(handler, exceptionCallback));
    }
    final ServerHttp1StreamDuplexerFactory streamHandlerFactory = new ServerHttp1StreamDuplexerFactory(httpProcessor != null ? httpProcessor : HttpProcessors.server(), handlerFactory, http1Config != null ? http1Config : Http1Config.DEFAULT, charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT, connStrategy != null ? connStrategy : DefaultConnectionReuseStrategy.INSTANCE, DefaultHttpRequestParserFactory.INSTANCE, DefaultHttpResponseWriterFactory.INSTANCE, DefaultContentLengthStrategy.INSTANCE, DefaultContentLengthStrategy.INSTANCE, streamListener);
    final IOEventHandlerFactory ioEventHandlerFactory = new ServerHttp1IOEventHandlerFactory(streamHandlerFactory, tlsStrategy, handshakeTimeout);
    return new HttpAsyncServer(ioEventHandlerFactory, ioReactorConfig, ioSessionDecorator, exceptionCallback, sessionListener);
}
Also used : AsyncServerFilterChainElement(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainElement) AsyncServerFilterChainExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainExchangeHandlerFactory) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) Args(org.apache.hc.core5.util.Args) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) CharCodingConfig(org.apache.hc.core5.http.config.CharCodingConfig) AsyncServerRequestHandler(org.apache.hc.core5.http.nio.AsyncServerRequestHandler) AsyncServerFilterChainElement(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainElement) BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) IOSessionListener(org.apache.hc.core5.reactor.IOSessionListener) Supplier(org.apache.hc.core5.function.Supplier) ArrayList(java.util.ArrayList) ServerHttp1IOEventHandlerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandlerFactory) HttpProcessor(org.apache.hc.core5.http.protocol.HttpProcessor) HttpProcessors(org.apache.hc.core5.http.impl.HttpProcessors) DefaultHttpResponseWriterFactory(org.apache.hc.core5.http.impl.nio.DefaultHttpResponseWriterFactory) LookupRegistry(org.apache.hc.core5.http.protocol.LookupRegistry) Http1Config(org.apache.hc.core5.http.config.Http1Config) NamedElementChain(org.apache.hc.core5.http.config.NamedElementChain) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler) AsyncFilterHandler(org.apache.hc.core5.http.nio.AsyncFilterHandler) BasicServerExchangeHandler(org.apache.hc.core5.http.nio.support.BasicServerExchangeHandler) Decorator(org.apache.hc.core5.function.Decorator) HandlerFactory(org.apache.hc.core5.http.nio.HandlerFactory) Callback(org.apache.hc.core5.function.Callback) ConnectionReuseStrategy(org.apache.hc.core5.http.ConnectionReuseStrategy) Timeout(org.apache.hc.core5.util.Timeout) DefaultContentLengthStrategy(org.apache.hc.core5.http.impl.DefaultContentLengthStrategy) UriPatternType(org.apache.hc.core5.http.protocol.UriPatternType) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory) List(java.util.List) DefaultHttpRequestParserFactory(org.apache.hc.core5.http.impl.nio.DefaultHttpRequestParserFactory) IOSession(org.apache.hc.core5.reactor.IOSession) TerminalAsyncServerFilter(org.apache.hc.core5.http.nio.support.TerminalAsyncServerFilter) InetAddressUtils(org.apache.hc.core5.net.InetAddressUtils) ServerHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory) TlsStrategy(org.apache.hc.core5.http.nio.ssl.TlsStrategy) AsyncServerExpectationFilter(org.apache.hc.core5.http.nio.support.AsyncServerExpectationFilter) DefaultAsyncResponseExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.DefaultAsyncResponseExchangeHandlerFactory) DefaultConnectionReuseStrategy(org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy) AsyncFilterHandler(org.apache.hc.core5.http.nio.AsyncFilterHandler) ServerHttp1StreamDuplexerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory) BasicAsyncServerExpectationDecorator(org.apache.hc.core5.http.nio.support.BasicAsyncServerExpectationDecorator) TerminalAsyncServerFilter(org.apache.hc.core5.http.nio.support.TerminalAsyncServerFilter) AsyncServerExpectationFilter(org.apache.hc.core5.http.nio.support.AsyncServerExpectationFilter) DefaultAsyncResponseExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.DefaultAsyncResponseExchangeHandlerFactory) NamedElementChain(org.apache.hc.core5.http.config.NamedElementChain) RequestHandlerRegistry(org.apache.hc.core5.http.protocol.RequestHandlerRegistry) Supplier(org.apache.hc.core5.function.Supplier) AsyncServerFilterChainExchangeHandlerFactory(org.apache.hc.core5.http.nio.support.AsyncServerFilterChainExchangeHandlerFactory) ServerHttp1IOEventHandlerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandlerFactory) IOEventHandlerFactory(org.apache.hc.core5.reactor.IOEventHandlerFactory) ServerHttp1IOEventHandlerFactory(org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandlerFactory) AsyncServerExchangeHandler(org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)

Example 4 with HttpAsyncServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer in project httpcomponents-core by apache.

the class AsyncReverseProxyExample method main.

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <hostname[:port]> [listener port] [--quiet]");
        System.exit(1);
    }
    // Target host
    final HttpHost targetHost = HttpHost.create(args[0]);
    int port = 8080;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    for (final String s : args) {
        if ("--quiet".equalsIgnoreCase(s)) {
            quiet = true;
            break;
        }
    }
    println("Reverse proxy to " + targetHost);
    final IOReactorConfig config = IOReactorConfig.custom().setSoTimeout(1, TimeUnit.MINUTES).build();
    final HttpAsyncRequester requester = AsyncRequesterBootstrap.bootstrap().setIOReactorConfig(config).setConnPoolListener(new ConnPoolListener<HttpHost>() {

        @Override
        public void onLease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] connection leased ").append(route);
            println(buf.toString());
        }

        @Override
        public void onRelease(final HttpHost route, final ConnPoolStats<HttpHost> connPoolStats) {
            final StringBuilder buf = new StringBuilder();
            buf.append("[proxy->origin] connection released ").append(route);
            final PoolStats totals = connPoolStats.getTotalStats();
            buf.append("; total kept alive: ").append(totals.getAvailable()).append("; ");
            buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
            buf.append(" of ").append(totals.getMax());
            println(buf.toString());
        }
    }).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[proxy<-origin] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).setMaxTotal(100).setDefaultMaxPerRoute(20).create();
    final HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
        // empty
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
        // empty
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            println("[client<-proxy] connection " + connection.getLocalAddress() + "->" + connection.getRemoteAddress() + (keepAlive ? " kept alive" : " cannot be kept alive"));
        }
    }).register("*", () -> new IncomingExchangeHandler(targetHost, requester)).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        println("Reverse proxy shutting down");
        server.close(CloseMode.GRACEFUL);
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    server.start();
    server.listen(new InetSocketAddress(port), URIScheme.HTTP);
    println("Listening on port " + port);
    server.awaitShutdown(TimeValue.MAX_VALUE);
}
Also used : BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) HttpResponse(org.apache.hc.core5.http.HttpResponse) BasicHttpResponse(org.apache.hc.core5.http.message.BasicHttpResponse) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) PoolStats(org.apache.hc.core5.pool.PoolStats) ConnPoolStats(org.apache.hc.core5.pool.ConnPoolStats) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) HttpAsyncServer(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer) HttpHost(org.apache.hc.core5.http.HttpHost) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester)

Example 5 with HttpAsyncServer

use of org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer in project httpcomponents-core by apache.

the class AsyncFullDuplexServerExample 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 HttpAsyncServer server = AsyncServerBootstrap.bootstrap().setIOReactorConfig(config).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)");
            }
        }
    }).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.MAX_VALUE);
}
Also used : SocketException(java.net.SocketException) HttpConnection(org.apache.hc.core5.http.HttpConnection) InetSocketAddress(java.net.InetSocketAddress) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) DataStreamChannel(org.apache.hc.core5.http.nio.DataStreamChannel) ResponseChannel(org.apache.hc.core5.http.nio.ResponseChannel) IOReactorConfig(org.apache.hc.core5.reactor.IOReactorConfig) 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) StatusLine(org.apache.hc.core5.http.message.StatusLine) RequestLine(org.apache.hc.core5.http.message.RequestLine) 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)

Aggregations

HttpAsyncServer (org.apache.hc.core5.http.impl.bootstrap.HttpAsyncServer)9 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)9 InetSocketAddress (java.net.InetSocketAddress)8 HttpRequest (org.apache.hc.core5.http.HttpRequest)7 ListenerEndpoint (org.apache.hc.core5.reactor.ListenerEndpoint)6 HttpConnection (org.apache.hc.core5.http.HttpConnection)5 HttpResponse (org.apache.hc.core5.http.HttpResponse)5 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)5 BasicHttpResponse (org.apache.hc.core5.http.message.BasicHttpResponse)5 AsyncServerRequestHandler (org.apache.hc.core5.http.nio.AsyncServerRequestHandler)5 List (java.util.List)4 EntityDetails (org.apache.hc.core5.http.EntityDetails)4 AsyncServerExchangeHandler (org.apache.hc.core5.http.nio.AsyncServerExchangeHandler)4 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)4 Message (org.apache.hc.core5.http.Message)3 BasicRequestConsumer (org.apache.hc.core5.http.nio.support.BasicRequestConsumer)3 File (java.io.File)2 IOException (java.io.IOException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2