Example usage for io.netty.handler.ssl.util SelfSignedCertificate certificate

List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate certificate

Introduction

In this page you can find the example usage for io.netty.handler.ssl.util SelfSignedCertificate certificate.

Prototype

File certificate

To view the source code for io.netty.handler.ssl.util SelfSignedCertificate certificate.

Click Source Link

Usage

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.server.StandbyServer.java

License:Apache License

public StandbyServer(int port, final SegmentStore store, String[] allowedClientIPRanges, boolean secure)
        throws CertificateException, SSLException {
    this.port = port;

    if (secure) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    }/* w w w . jav a2s  .  com*/

    observer = new CommunicationObserver("primary");
    handler = new StandbyServerHandler(store, observer, allowedClientIPRanges);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    final MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    try {
        jmxServer.registerMBean(new StandardMBean(this, StandbyStatusMBean.class),
                new ObjectName(this.getMBeanName()));
    } catch (Exception e) {
        log.error("can't register standby status mbean", e);
    }

    b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);

    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.SO_REUSEADDR, true);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslContext != null) {
                p.addLast(sslContext.newHandler(ch.alloc()));
            }
            p.addLast(new LineBasedFrameDecoder(8192));
            p.addLast(new StringDecoder(CharsetUtil.UTF_8));
            p.addLast(new SnappyFramedEncoder());
            p.addLast(new RecordIdEncoder());
            p.addLast(new SegmentEncoder());
            p.addLast(new BlobEncoder());
            p.addLast(handler);
        }
    });
}

From source file:org.apache.rocketmq.remoting.netty.TlsHelper.java

License:Apache License

public static SslContext buildSslContext(boolean forClient) throws IOException, CertificateException {
    File configFile = new File(TlsSystemConfig.tlsConfigFile);
    extractTlsConfigFromFile(configFile);
    logTheFinalUsedTlsConfig();//from  ww w  . j  av  a2s  . c o  m

    SslProvider provider;
    if (OpenSsl.isAvailable()) {
        provider = SslProvider.OPENSSL;
        LOGGER.info("Using OpenSSL provider");
    } else {
        provider = SslProvider.JDK;
        LOGGER.info("Using JDK SSL provider");
    }

    if (forClient) {
        if (tlsTestModeEnable) {
            return SslContextBuilder.forClient().sslProvider(SslProvider.JDK)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK);

            if (!tlsClientAuthServer) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsClientTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsClientTrustCertPath));
                }
            }

            return sslContextBuilder
                    .keyManager(
                            !isNullOrEmpty(tlsClientCertPath) ? new FileInputStream(tlsClientCertPath) : null,
                            !isNullOrEmpty(tlsClientKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsClientKeyPath, true)
                                    : null,
                            !isNullOrEmpty(tlsClientKeyPassword) ? tlsClientKeyPassword : null)
                    .build();
        }
    } else {

        if (tlsTestModeEnable) {
            SelfSignedCertificate selfSignedCertificate = new SelfSignedCertificate();
            return SslContextBuilder
                    .forServer(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey())
                    .sslProvider(SslProvider.JDK).clientAuth(ClientAuth.OPTIONAL).build();
        } else {
            SslContextBuilder sslContextBuilder = SslContextBuilder
                    .forServer(
                            !isNullOrEmpty(tlsServerCertPath) ? new FileInputStream(tlsServerCertPath) : null,
                            !isNullOrEmpty(tlsServerKeyPath)
                                    ? decryptionStrategy.decryptPrivateKey(tlsServerKeyPath, false)
                                    : null,
                            !isNullOrEmpty(tlsServerKeyPassword) ? tlsServerKeyPassword : null)
                    .sslProvider(provider);

            if (!tlsServerAuthClient) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                if (!isNullOrEmpty(tlsServerTrustCertPath)) {
                    sslContextBuilder.trustManager(new File(tlsServerTrustCertPath));
                }
            }

            sslContextBuilder.clientAuth(parseClientAuthMode(tlsServerNeedClientAuth));
            return sslContextBuilder.build();
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.AbstractChannelizer.java

License:Apache License

private SslContext createSSLContext(final Settings settings) {
    final Settings.SslSettings sslSettings = settings.ssl;

    if (sslSettings.getSslContext().isPresent()) {
        logger.info("Using the SslContext override");
        return sslSettings.getSslContext().get();
    }// www  .ja va 2  s. c o  m

    final SslProvider provider = SslProvider.JDK;

    final SslContextBuilder builder;

    // if the config doesn't contain a cert or key then use a self signed cert - not suitable for production
    if (null == sslSettings.keyCertChainFile || null == sslSettings.keyFile) {
        try {
            logger.warn("Enabling SSL with self-signed certificate (NOT SUITABLE FOR PRODUCTION)");
            final SelfSignedCertificate ssc = new SelfSignedCertificate();
            builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ce) {
            logger.error("There was an error creating the self-signed certificate for SSL - SSL is not enabled",
                    ce);
            return null;
        }
    } else {
        final File keyCertChainFile = new File(sslSettings.keyCertChainFile);
        final File keyFile = new File(sslSettings.keyFile);
        final File trustCertChainFile = null == sslSettings.trustCertChainFile ? null
                : new File(sslSettings.trustCertChainFile);

        // note that keyPassword may be null here if the keyFile is not password-protected. passing null to
        // trustManager is also ok (default will be used)
        builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, sslSettings.keyPassword)
                .trustManager(trustCertChainFile);
    }

    builder.sslProvider(provider);

    try {
        return builder.build();
    } catch (SSLException ssle) {
        logger.error("There was an error enabling SSL", ssle);
        return null;
    }
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

License:Apache License

private static SslContext createServerSslContext() {
    final SslProvider provider = SslProvider.JDK;

    try {/*from  www .  j a  va2  s  .c o m*/
        // this is not good for production - just testing
        final SelfSignedCertificate ssc = new SelfSignedCertificate();
        return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).build();
    } catch (Exception ce) {
        throw new RuntimeException("Couldn't setup self-signed certificate for test");
    }
}

From source file:org.artJava.chat.SecureChatServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    //SelfSignedCertificate
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    ////from w w  w.  j a  v a  2 s  .  c o  m
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();//
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
        //bindchannnel
        //syncfuture futurefuture
        //channel futureiochannel
        //closefuture future
        //

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.atmosphere.nettosphere.test.NettyAtmosphereTest.java

License:Apache License

@Test
public void nettySslContextTest() throws Exception {
    final CountDownLatch l = new CountDownLatch(1);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

    Config config = new Config.Builder().port(port).host("127.0.0.1").sslContext(sslCtx)
            .resource(new Handler() {

                @Override/* www.ja  v a2 s.c o  m*/
                public void handle(AtmosphereResource r) {
                    r.getResponse().write("Hello World from Nettosphere").closeStreamOrWriter();
                }
            }).build();

    server = new Nettosphere.Builder().config(config).build();
    assertNotNull(server);
    server.start();

    AsyncHttpClient c = new AsyncHttpClient(
            new AsyncHttpClientConfig.Builder().setAcceptAnyCertificate(true).build());
    try {
        final AtomicReference<String> response = new AtomicReference<String>();
        WebSocket webSocket = c.prepareGet("wss://127.0.0.1:" + port)
                .execute(new WebSocketUpgradeHandler.Builder().build()).get();
        assertNotNull(webSocket);
        webSocket.addWebSocketListener(new WebSocketTextListener() {
            @Override
            public void onMessage(String message) {
                response.set(message);
                l.countDown();
            }

            @Override
            public void onOpen(WebSocket websocket) {
            }

            @Override
            public void onClose(WebSocket websocket) {
            }

            @Override
            public void onError(Throwable t) {
            }
        });

        l.await(5, TimeUnit.SECONDS);

        webSocket.close();
        assertEquals(response.get(), "Hello World from Nettosphere");
    } finally {
        c.close();
    }
}

From source file:org.betawares.jorre.Server.java

License:Open Source License

/**
 * Starts the Server with the specified {@link Connection} settings.
 * //from  w ww  .j  a va  2 s  .  com
 * @param connection  a {@link Connection} instance specifying the connection settings
 * 
 * @throws Exception  thrown if there is an error starting the server
 */
public void start(Connection connection) throws Exception {

    SslContext sslCtx;

    if (connection.isSSL()) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    if (sslCtx != null) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    ch.pipeline()
                            .addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null)));
                    ch.pipeline().addLast(encoder);
                    ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(),
                            connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast(handlersExecutor, "heartbeatHandler",
                            new ServerHeartbeatHandler(Server.this));
                    ch.pipeline().addLast("pingMessageHandler", pingMessageHandler);
                    ch.pipeline().addLast("pongMessageHandler", pongMessageHandler);

                    ch.pipeline().addLast("connectionHandler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            clients.add(ctx.channel());
                            ctx.pipeline().remove(this);
                            super.channelActive(ctx);
                        }
                    });
                    ch.pipeline().addLast(handlersExecutor, "serverMessageHandler", serverRequestHandler);
                    ch.pipeline().addLast("exceptionHandler", exceptionHandler);
                }
            });
    bootstrap.bind(connection.getPort()).sync();

}

From source file:org.caffinitas.prometheusmetrics.PrometheusMetricsExporter.java

License:Apache License

private void setupNetty() throws CertificateException, SSLException {
    final SslContext sslCtx;
    if (config.ssl) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        LOGGER.info("Setting up SSL context for certificate subject DN {} valid until {}",
                ssc.cert().getSubjectDN(), ssc.cert().getNotAfter());
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {//w w w.j a  va 2  s  .  c  o  m
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    this.nettyChannel = new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 1024)
            .group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerInitializer(sslCtx)).bind(config.bindAddress, config.httpPort)
            .syncUninterruptibly().channel();

    nettyChannel.closeFuture().addListener(f -> {
        LOGGER.info("Shutting down listener");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    });
}

From source file:org.curioswitch.common.server.framework.armeria.ClientBuilderFactory.java

License:Open Source License

@Inject
public ClientBuilderFactory(MeterRegistry meterRegistry, Tracing tracing,
        Function<Client<HttpRequest, HttpResponse>, LoggingClient<HttpRequest, HttpResponse>> loggingClient,
        Optional<SelfSignedCertificate> selfSignedCertificate, Optional<TrustManagerFactory> caTrustManager,
        Lazy<Factory> googleCredentialsDecoratingClient, ServerConfig serverConfig) {
    this.tracing = tracing;
    this.meterRegistry = meterRegistry;
    this.loggingClient = loggingClient;
    final TrustManagerFactory trustManagerFactory;
    if (serverConfig.isDisableClientCertificateVerification()) {
        logger.warn("Disabling client SSL verification. This should only happen on local!");
        trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    } else if (caTrustManager.isPresent()) {
        trustManagerFactory = caTrustManager.get();
    } else {/*w  ww .  ja  v a  2  s. c  om*/
        trustManagerFactory = null;
    }

    final Consumer<SslContextBuilder> clientCertificateCustomizer;
    if (selfSignedCertificate.isPresent()) {
        SelfSignedCertificate certificate = selfSignedCertificate.get();
        clientCertificateCustomizer = sslContext -> sslContext.keyManager(certificate.certificate(),
                certificate.privateKey());
    } else if (serverConfig.getTlsCertificatePath().isEmpty()
            || serverConfig.getTlsPrivateKeyPath().isEmpty()) {
        throw new IllegalStateException(
                "No TLS configuration provided, Curiostack does not support clients without TLS "
                        + "certificates. Use gradle-curio-cluster-plugin to set up a namespace and TLS.");
    } else {
        String certPath = !serverConfig.getClientTlsCertificatePath().isEmpty()
                ? serverConfig.getClientTlsCertificatePath()
                : serverConfig.getTlsCertificatePath();
        String keyPath = !serverConfig.getClientTlsPrivateKeyPath().isEmpty()
                ? serverConfig.getClientTlsPrivateKeyPath()
                : serverConfig.getTlsPrivateKeyPath();
        clientCertificateCustomizer = sslContext -> SslContextKeyConverter.execute(
                ResourceUtil.openStream(certPath), ResourceUtil.openStream(keyPath), sslContext::keyManager);
    }

    final Consumer<SslContextBuilder> clientTlsCustomizer;
    if (trustManagerFactory != null) {
        clientTlsCustomizer = sslContext -> {
            clientCertificateCustomizer.accept(sslContext);
            sslContext.trustManager(trustManagerFactory);
        };
    } else {
        clientTlsCustomizer = clientCertificateCustomizer;
    }
    ClientFactoryBuilder factoryBuilder = new ClientFactoryBuilder().sslContextCustomizer(clientTlsCustomizer)
            .meterRegistry(meterRegistry);
    if (serverConfig.getDisableEdns()) {
        factoryBuilder.addressResolverGroupFactory(eventLoopGroup -> new DnsAddressResolverGroup(
                new DnsNameResolverBuilder().channelType(TransportType.datagramChannelType(eventLoopGroup))
                        .nameServerProvider(DnsServerAddressStreamProviders.platformDefault())
                        .optResourceEnabled(false)));
    }
    clientFactory = factoryBuilder.build();
}

From source file:org.curioswitch.common.server.framework.ServerModule.java

License:Open Source License

@SuppressWarnings("FutureReturnValueIgnored")
@Provides/*from   w ww .  j a v a 2s .c o  m*/
@Singleton
static Server armeriaServer(Set<BindableService> grpcServices,
        Set<GrpcServiceDefinition> grpcServiceDefinitions, Set<HttpServiceDefinition> httpServiceDefinitions,
        Set<StaticSiteServiceDefinition> staticSites, Set<Consumer<ServerBuilder>> serverCustomizers,
        Set<PostServerCustomizer> postServerCustomizers, Set<WatchedPath> watchedPaths,
        Function<Service<HttpRequest, HttpResponse>, LoggingService<HttpRequest, HttpResponse>> loggingService,
        MetricsHttpService metricsHttpService, CollectorRegistry collectorRegistry, MeterRegistry meterRegistry,
        Tracing tracing, Lazy<FirebaseAuthorizer> firebaseAuthorizer, Lazy<JwtAuthorizer.Factory> jwtAuthorizer,
        Lazy<JavascriptStaticService> javascriptStaticService,
        Optional<SelfSignedCertificate> selfSignedCertificate, Optional<TrustManagerFactory> caTrustManager,
        Optional<SslCommonNamesProvider> sslCommonNamesProvider, FileWatcher.Builder fileWatcherBuilder,
        Lazy<StackdriverReporter> stackdriverReporter, ServerConfig serverConfig, FirebaseAuthConfig authConfig,
        HttpsOnlyService.Factory httpsOnlyServiceFactory, JavascriptStaticConfig javascriptStaticConfig,
        MonitoringConfig monitoringConfig, SecurityConfig securityConfig,
        Set<ServerShutDownDelayer> serverShutDownDelayers, @CloseOnStop Set<Closeable> closeOnStopDependencies,
        // Eagerly trigger bindings that are present, not actually used here.
        @EagerInit Set<Object> eagerInitializedDependencies) {
    for (WatchedPath watched : watchedPaths) {
        fileWatcherBuilder.registerPath(watched.getPath(), watched.getHandler());
    }

    if (!sslCommonNamesProvider.isPresent() && !serverConfig.getRpcAclsPath().isEmpty()
            && !serverConfig.isDisableSslAuthorization()) {
        Path path = Paths.get(serverConfig.getRpcAclsPath()).toAbsolutePath();
        RpcAclsCommonNamesProvider commonNamesProvider = new RpcAclsCommonNamesProvider(path);
        fileWatcherBuilder.registerPath(path, commonNamesProvider::processFile);
        if (path.toFile().exists()) {
            commonNamesProvider.processFile(path);
        }
        sslCommonNamesProvider = Optional.of(commonNamesProvider);
    }

    ServerBuilder sb = new ServerBuilder().https(serverConfig.getPort());

    if (selfSignedCertificate.isPresent()) {
        SelfSignedCertificate certificate = selfSignedCertificate.get();
        try {
            SslContextBuilder sslContext = serverSslContext(
                    ResourceUtil.openStream(certificate.certificate().getAbsolutePath()),
                    ResourceUtil.openStream(certificate.privateKey().getAbsolutePath()))
                            .trustManager(InsecureTrustManagerFactory.INSTANCE);
            if (!serverConfig.isDisableSslAuthorization()) {
                sslContext.clientAuth(ClientAuth.OPTIONAL);
            }
            sb.tls(sslContext.build());
        } catch (SSLException e) {
            // Can't happen.
            throw new IllegalStateException(e);
        }
    } else if (serverConfig.getTlsCertificatePath().isEmpty() || serverConfig.getTlsPrivateKeyPath().isEmpty()
            || !caTrustManager.isPresent()) {
        throw new IllegalStateException(
                "No TLS configuration provided, Curiostack does not support non-TLS servers. "
                        + "Use gradle-curio-cluster-plugin to set up a namespace and TLS.");
    } else {
        try {
            SslContextBuilder sslContext = serverSslContext(
                    ResourceUtil.openStream(serverConfig.getTlsCertificatePath()),
                    ResourceUtil.openStream(serverConfig.getTlsPrivateKeyPath()))
                            .trustManager(caTrustManager.get());
            if (!serverConfig.isDisableSslAuthorization()) {
                sslContext.clientAuth(ClientAuth.OPTIONAL);
            }
            sb.tls(sslContext.build());
        } catch (SSLException e) {
            throw new IllegalStateException("Could not load TLS certificate.", e);
        }
    }

    serverCustomizers.forEach(c -> c.accept(sb));

    Optional<Function<Service<HttpRequest, HttpResponse>, IpFilteringService>> ipFilter = Optional.empty();
    if (!serverConfig.getIpFilterRules().isEmpty()) {
        ipFilter = Optional.of(IpFilteringService.newDecorator(serverConfig.getIpFilterRules()));
    }

    if (!serverConfig.isDisableDocService()) {
        DocServiceBuilder docService = new DocServiceBuilder();
        if (!authConfig.getServiceAccountBase64().isEmpty()) {
            docService.injectedScript("armeria.registerHeaderProvider(function() {\n"
                    + "  return firebase.auth().currentUser.getIdToken().then(token => { authorization: 'bearer ' + token });\n"
                    + "});");
        }
        sb.serviceUnder("/internal/docs", internalService(docService.build(), ipFilter, serverConfig));
    }

    SettableHealthChecker settableHealthChecker = new SettableHealthChecker(true);
    List<HealthChecker> healthCheckers = serverShutDownDelayers.isEmpty() ? ImmutableList.of()
            : ImmutableList.of(settableHealthChecker);

    sb.service("/internal/health",
            internalService(new HttpHealthCheckService(healthCheckers), ipFilter, serverConfig));
    sb.service("/internal/dropwizard", internalService(metricsHttpService, ipFilter, serverConfig));
    sb.service("/internal/metrics",
            internalService(new PrometheusExpositionService(collectorRegistry), ipFilter, serverConfig));
    if (sslCommonNamesProvider.isPresent()) {
        SslCommonNamesProvider namesProvider = sslCommonNamesProvider.get();
        sb.service("/internal/rpcacls", internalService((ctx, req) -> HttpResponse.of(HttpStatus.OK,
                MediaType.PLAIN_TEXT_UTF_8, String.join("\n", namesProvider.get())), ipFilter, serverConfig));
    }

    if (!grpcServices.isEmpty()) {
        GrpcServiceDefinition definition = new GrpcServiceDefinition.Builder().addAllServices(grpcServices)
                .decorator(Function.identity()).path(serverConfig.getGrpcPath()).build();
        grpcServiceDefinitions = ImmutableSet.<GrpcServiceDefinition>builder().addAll(grpcServiceDefinitions)
                .add(definition).build();
    }

    for (GrpcServiceDefinition definition : grpcServiceDefinitions) {
        GrpcServiceBuilder serviceBuilder = new GrpcServiceBuilder()
                .supportedSerializationFormats(GrpcSerializationFormats.values()).enableUnframedRequests(true);
        definition.services().forEach(serviceBuilder::addService);
        if (!serverConfig.isDisableGrpcServiceDiscovery()) {
            serviceBuilder.addService(ProtoReflectionService.newInstance());
        }
        definition.customizer().accept(serviceBuilder);
        ServiceWithRoutes<HttpRequest, HttpResponse> service = serviceBuilder.build();
        if (definition.path().equals("/")) {
            Optional<SslCommonNamesProvider> sslCommonNamesProvider0 = sslCommonNamesProvider;
            sb.service(service, s -> decorateService(s.decorate(definition.decorator()), tracing,
                    firebaseAuthorizer, jwtAuthorizer, sslCommonNamesProvider0, serverConfig, authConfig));
        } else {
            sb.serviceUnder(definition.path(),
                    decorateService(service.decorate(definition.decorator()), tracing, firebaseAuthorizer,
                            jwtAuthorizer, sslCommonNamesProvider, serverConfig, authConfig));
        }
    }

    for (HttpServiceDefinition definition : httpServiceDefinitions) {
        sb.service(definition.route(), decorateService(definition.service(), tracing, firebaseAuthorizer,
                jwtAuthorizer, sslCommonNamesProvider, serverConfig, authConfig));
    }

    if (javascriptStaticConfig.getVersion() != 0) {
        sb.service("/static/jsconfig-" + javascriptStaticConfig.getVersion(), javascriptStaticService.get());
    }

    for (StaticSiteServiceDefinition staticSite : staticSites) {
        sb.serviceUnder(staticSite.urlRoot(),
                StaticSiteService.of(staticSite.staticPath(), staticSite.classpathRoot()));
    }

    if (ipFilter.isPresent() && !serverConfig.getIpFilterInternalOnly()) {
        sb.decorator(ipFilter.get());
    }

    if (securityConfig.getHttpsOnly()) {
        sb.decorator(httpsOnlyServiceFactory.newDecorator());
    }

    sb.decorator(loggingService);
    sb.meterRegistry(meterRegistry);

    if (serverConfig.getEnableGracefulShutdown()) {
        sb.gracefulShutdownTimeout(Duration.ofSeconds(10), Duration.ofSeconds(30));
    }

    postServerCustomizers.forEach((c) -> c.accept(sb));

    sb.serverListener(new ServerListener() {
        @Override
        public void serverStarting(Server server) {
        }

        @Override
        public void serverStarted(Server server) {
        }

        @Override
        public void serverStopping(Server server) {
        }

        @Override
        public void serverStopped(Server server) {
            closeOnStopDependencies.forEach(c -> {
                try {
                    c.close();
                } catch (IOException e) {
                    logger.info("Exception closing {}", c);
                }
            });
        }
    });

    Server server = sb.build();
    server.start().whenComplete((unused, t) -> {
        if (t != null) {
            logger.error("Error starting server.", t);
        } else {
            logger.info("Server started on ports: " + server.activePorts());
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        logger.info("Received shutdown signal.");

        settableHealthChecker.setHealthy(false);

        if (!serverShutDownDelayers.isEmpty()) {
            Futures.getUnchecked(Futures.successfulAsList(serverShutDownDelayers.stream()
                    .map(ServerShutDownDelayer::readyForShutdown).collect(toImmutableList())));
        }

        logger.info("Server shutting down.");
        server.stop().join();
    }));

    if (!fileWatcherBuilder.isEmpty()) {
        FileWatcher fileWatcher = fileWatcherBuilder.build();
        fileWatcher.start();
        Runtime.getRuntime().addShutdownHook(new Thread(fileWatcher::close));
    }

    if (monitoringConfig.isReportTraces()) {
        server.nextEventLoop().scheduleAtFixedRate(stackdriverReporter.get()::flush, 0,
                monitoringConfig.getTraceReportInterval().getSeconds(), TimeUnit.SECONDS);
    }

    return server;
}