Example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

List of usage examples for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ThreadFactoryBuilder ThreadFactoryBuilder.

Prototype

public ThreadFactoryBuilder() 

Source Link

Document

Creates a new ThreadFactory builder.

Usage

From source file:io.bitsquare.monitor.MonitorMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("MonitorMain").setDaemon(true)
            .build();//from ww w.  ja v a  2 s .c  om
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_monitor");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(MonitorMain.class.getClassLoader());

    new MonitorMain().execute(args);
}

From source file:io.bitsquare.headless.HeadlessMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("HeadlessMain").setDaemon(true)
            .build();/*from   ww w  . j  ava 2s  .co m*/
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_headless");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(HeadlessMain.class.getClassLoader());

    new HeadlessMain().execute(args);
}

From source file:io.bitsquare.seednode.SeedNodeMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("SeedNodeMain").setDaemon(true)
            .build();/*from ww w . j ava 2  s  .  c  o m*/
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_seednode");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(SeedNodeMain.class.getClassLoader());

    new SeedNodeMain().execute(args);
}

From source file:io.bitsquare.statistics.StatisticsMain.java

public static void main(String[] args) throws Exception {
    final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Statistics").setDaemon(true)
            .build();/*w w  w  .ja va  2s .com*/
    UserThread.setExecutor(Executors.newSingleThreadExecutor(threadFactory));

    // We don't want to do the full argument parsing here as that might easily change in update versions
    // So we only handle the absolute minimum which is APP_NAME, APP_DATA_DIR_KEY and USER_DATA_DIR
    BitsquareEnvironment.setDefaultAppName("Bitsquare_statistics");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.accepts(AppOptionKeys.USER_DATA_DIR_KEY, description("User data directory", DEFAULT_USER_DATA_DIR))
            .withRequiredArg();
    parser.accepts(AppOptionKeys.APP_NAME_KEY, description("Application name", DEFAULT_APP_NAME))
            .withRequiredArg();

    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException ex) {
        System.out.println("error: " + ex.getMessage());
        System.out.println();
        parser.printHelpOn(System.out);
        System.exit(EXIT_FAILURE);
        return;
    }
    BitsquareEnvironment bitsquareEnvironment = new BitsquareEnvironment(options);

    // need to call that before BitsquareAppMain().execute(args)
    BitsquareExecutable.initAppDir(bitsquareEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY));

    // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it.
    // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method:
    Thread.currentThread().setContextClassLoader(StatisticsMain.class.getClassLoader());

    new StatisticsMain().execute(args);
}

From source file:org.glowroot.agent.it.harness.impl.JavaagentMain.java

public static void main(String[] args) throws Exception {

    // this is needed on Java 9+ now that sun.boot.class.path no longer exists, so that
    // instrumentation config auto complete can find this class in InstrumentationConfigIT
    Reflection.initialize(Container.class);

    int port = Integer.parseInt(args[0]);
    final SocketHeartbeat socketHeartbeat = new SocketHeartbeat(port);
    new Thread(socketHeartbeat).start();

    int javaagentServicePort = Integer.parseInt(args[1]);
    JavaagentServiceImpl javaagentService = new JavaagentServiceImpl();
    final EventLoopGroup bossEventLoopGroup = EventLoopGroups.create("Glowroot-IT-Harness*-GRPC-Boss-ELG");
    final EventLoopGroup workerEventLoopGroup = EventLoopGroups.create("Glowroot-IT-Harness*-GRPC-Worker-ELG");
    // need at least 2 threads, one for executeApp(), and another for handling interruptApp() at
    // the same time
    final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-IT-Harness*-GRPC-Executor-%d").build());
    final Server server = NettyServerBuilder.forPort(javaagentServicePort)
            .bossEventLoopGroup(bossEventLoopGroup).workerEventLoopGroup(workerEventLoopGroup)
            .executor(executor).addService(javaagentService.bindService()).build().start();
    javaagentService.setServerCloseable(new Callable</*@Nullable*/ Void>() {
        @Override/*from ww  w.  j a  v a2 s .c  o  m*/
        public @Nullable Void call() throws Exception {
            server.shutdown();
            if (!server.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate channel");
            }
            executor.shutdown();
            if (!executor.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate executor");
            }
            if (!bossEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate gRPC boss event loop group");
            }
            if (!workerEventLoopGroup.shutdownGracefully(0, 0, SECONDS).await(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate gRPC worker event loop group");
            }
            socketHeartbeat.close();
            return null;
        }
    });

    // spin a bit to so that caller can capture a trace with <multiple root nodes> if desired
    for (int i = 0; i < 1000; i++) {
        timerMarkerOne();
        timerMarkerTwo();
        MILLISECONDS.sleep(1);
    }
    // non-daemon threads started above keep jvm alive after main returns
    MILLISECONDS.sleep(Long.MAX_VALUE);
}

From source file:org.apache.pulsar.compaction.CompactorTool.java

public static void main(String[] args) throws Exception {
    Arguments arguments = new Arguments();
    JCommander jcommander = new JCommander(arguments);
    jcommander.setProgramName("PulsarTopicCompactor");

    // parse args by JCommander
    jcommander.parse(args);/*w w  w .j a v  a2s  .  c  o  m*/
    if (arguments.help) {
        jcommander.usage();
        System.exit(-1);
    }

    // init broker config
    ServiceConfiguration brokerConfig;
    if (isBlank(arguments.brokerConfigFile)) {
        jcommander.usage();
        throw new IllegalArgumentException("Need to specify a configuration file for broker");
    } else {
        brokerConfig = PulsarConfigurationLoader.create(arguments.brokerConfigFile, ServiceConfiguration.class);
    }

    ClientBuilder clientBuilder = PulsarClient.builder();

    if (isNotBlank(brokerConfig.getBrokerClientAuthenticationPlugin())) {
        clientBuilder.authentication(brokerConfig.getBrokerClientAuthenticationPlugin(),
                brokerConfig.getBrokerClientAuthenticationParameters());
    }

    if (brokerConfig.getBrokerServicePortTls().isPresent()) {
        clientBuilder.serviceUrl(PulsarService.brokerUrlTls(brokerConfig))
                .allowTlsInsecureConnection(brokerConfig.isTlsAllowInsecureConnection())
                .tlsTrustCertsFilePath(brokerConfig.getTlsCertificateFilePath());

    } else {
        clientBuilder.serviceUrl(PulsarService.brokerUrl(brokerConfig));
    }

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(
            new ThreadFactoryBuilder().setNameFormat("compaction-%d").setDaemon(true).build());

    OrderedScheduler executor = OrderedScheduler.newSchedulerBuilder().build();
    ZooKeeperClientFactory zkClientFactory = new ZookeeperBkClientFactoryImpl(executor);

    ZooKeeper zk = zkClientFactory.create(brokerConfig.getZookeeperServers(),
            ZooKeeperClientFactory.SessionType.ReadWrite, (int) brokerConfig.getZooKeeperSessionTimeoutMillis())
            .get();
    BookKeeperClientFactory bkClientFactory = new BookKeeperClientFactoryImpl();
    BookKeeper bk = bkClientFactory.create(brokerConfig, zk);
    try (PulsarClient pulsar = clientBuilder.build()) {
        Compactor compactor = new TwoPhaseCompactor(brokerConfig, pulsar, bk, scheduler);
        long ledgerId = compactor.compact(arguments.topic).get();
        log.info("Compaction of topic {} complete. Compacted to ledger {}", arguments.topic, ledgerId);
    } finally {
        bk.close();
        bkClientFactory.close();
        zk.close();
        scheduler.shutdownNow();
        executor.shutdown();
    }
}

From source file:io.codis.nedis.bench.JedisBench.java

public static void main(String[] args) throws InterruptedException {
    Args parsedArgs = new Args();
    CmdLineParser parser = new CmdLineParser(parsedArgs);
    try {// w w  w  .  java  2 s.  c o m
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        parser.printUsage(System.err);
        return;
    }

    AtomicBoolean stop = new AtomicBoolean(false);
    AtomicLong reqCount = new AtomicLong(0);
    ExecutorService executor = Executors.newFixedThreadPool(parsedArgs.threads,
            new ThreadFactoryBuilder().setDaemon(true).build());
    HostAndPort hap = HostAndPort.fromString(parsedArgs.redisAddr);
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(parsedArgs.conns);
    config.setMaxIdle(parsedArgs.conns);
    JedisPool pool = new JedisPool(config, hap.getHostText(), hap.getPort());
    for (int i = 0; i < parsedArgs.threads; i++) {
        executor.execute(new Worker(stop, reqCount, pool, parsedArgs.pipeline));
    }
    long duration = TimeUnit.MINUTES.toNanos(parsedArgs.minutes);
    long startTime = System.nanoTime();
    long prevTime = -1L;
    long prevReqCount = -1L;
    for (;;) {
        long currentTime = System.nanoTime();
        if (currentTime - startTime >= duration) {
            stop.set(true);
            executor.shutdown();
            if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                throw new RuntimeException("Can not terminate workers");
            }
            System.out.println(String.format("Test run %d minutes, qps: %.2f", parsedArgs.minutes,
                    (double) reqCount.get() / (currentTime - startTime) * TimeUnit.SECONDS.toNanos(1)));
            pool.close();
            return;
        }
        long currentReqCount = reqCount.get();
        if (prevTime > 0) {
            System.out.println(String.format("qps: %.2f", (double) (currentReqCount - prevReqCount)
                    / (currentTime - prevTime) * TimeUnit.SECONDS.toNanos(1)));
        }
        prevTime = currentTime;
        prevReqCount = currentReqCount;
        Thread.sleep(5000);
    }
}

From source file:io.codis.nedis.bench.NedisBench.java

public static void main(String[] args) throws InterruptedException {
    Args parsedArgs = new Args();
    CmdLineParser parser = new CmdLineParser(parsedArgs);
    try {/*from w  w  w  .  j a v  a2s  . c om*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        parser.printUsage(System.err);
        return;
    }

    AtomicBoolean stop = new AtomicBoolean(false);
    AtomicLong reqCount = new AtomicLong(0);
    ExecutorService executor = Executors.newFixedThreadPool(parsedArgs.threads,
            new ThreadFactoryBuilder().setDaemon(true).build());
    HostAndPort hap = HostAndPort.fromString(parsedArgs.redisAddr);
    NedisClient client = NedisUtils.newPooledClient(NedisClientPoolBuilder.create()
            .maxPooledConns(parsedArgs.conns).remoteAddress(hap.getHostText(), hap.getPort()).build());
    for (int i = 0; i < parsedArgs.threads; i++) {
        executor.execute(new Worker(stop, reqCount, client, parsedArgs.pipeline));
    }
    long duration = TimeUnit.MINUTES.toNanos(parsedArgs.minutes);
    long startTime = System.nanoTime();
    long prevTime = -1L;
    long prevReqCount = -1L;
    for (;;) {
        long currentTime = System.nanoTime();
        if (currentTime - startTime >= duration) {
            stop.set(true);
            executor.shutdown();
            if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                throw new RuntimeException("Can not terminate workers");
            }
            System.out.println(String.format("Test run %d minutes, qps: %.2f", parsedArgs.minutes,
                    (double) reqCount.get() / (currentTime - startTime) * TimeUnit.SECONDS.toNanos(1)));
            client.close().sync();
            return;
        }
        long currentReqCount = reqCount.get();
        if (prevTime > 0) {
            System.out.println(String.format("qps: %.2f", (double) (currentReqCount - prevReqCount)
                    / (currentTime - prevTime) * TimeUnit.SECONDS.toNanos(1)));
        }
        prevTime = currentTime;
        prevReqCount = currentReqCount;
        Thread.sleep(5000);
    }
}

From source file:org.apache.samza.rest.SamzaRestService.java

/**
 * Command line interface to run the server.
 *
 * @param args arguments supported by {@link org.apache.samza.util.CommandLine}.
 *             In particular, --config-path and --config-factory are used to read the Samza REST config file.
 * @throws Exception if the server could not be successfully started.
 *//*from   ww  w.ja  v a  2 s.c  o  m*/
public static void main(String[] args) throws Exception {
    ScheduledExecutorSchedulingProvider schedulingProvider = null;
    try {
        SamzaRestConfig config = parseConfig(args);
        ReadableMetricsRegistry metricsRegistry = new MetricsRegistryMap();
        log.info("Creating new SamzaRestService with config: {}", config);
        MetricsConfig metricsConfig = new MetricsConfig(config);
        Map<String, MetricsReporter> metricsReporters = MetricsReporterLoader.getMetricsReporters(metricsConfig,
                Util.getLocalHost().getHostName());
        SamzaRestService restService = new SamzaRestService(new Server(config.getPort()), metricsRegistry,
                metricsReporters, new ServletContextHandler(ServletContextHandler.SESSIONS));

        // Add applications
        SamzaRestApplication samzaRestApplication = new SamzaRestApplication(config);
        ServletContainer container = new ServletContainer(samzaRestApplication);
        restService.addServlet(container, "/*");

        // Schedule monitors to run
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true)
                .setNameFormat("MonitorThread-%d").build();
        ScheduledExecutorService schedulingService = Executors.newScheduledThreadPool(1, threadFactory);
        schedulingProvider = new ScheduledExecutorSchedulingProvider(schedulingService);
        SamzaMonitorService monitorService = new SamzaMonitorService(config, metricsRegistry,
                schedulingProvider);
        monitorService.start();

        restService.runBlocking();
        monitorService.stop();
    } catch (Throwable t) {
        log.error("Exception in main.", t);
    } finally {
        if (schedulingProvider != null) {
            schedulingProvider.stop();
        }
    }
}

From source file:com.metamx.druid.http.MasterMain.java

public static void main(String[] args) throws Exception {
    LogLevelAdjuster.register();//ww  w.j  av a2 s  . c  om

    final ObjectMapper jsonMapper = new DefaultObjectMapper();
    final Properties props = Initialization.loadProperties();
    final ConfigurationObjectFactory configFactory = Config.createFactory(props);
    final Lifecycle lifecycle = new Lifecycle();

    final HttpClientConfig.Builder httpClientConfigBuilder = HttpClientConfig.builder().withNumConnections(1);

    final String emitterTimeout = props.getProperty("druid.emitter.timeOut");
    if (emitterTimeout != null) {
        httpClientConfigBuilder.withReadTimeout(new Duration(emitterTimeout));
    }
    final HttpClient httpClient = HttpClientInit.createClient(httpClientConfigBuilder.build(), lifecycle);

    final ServiceEmitter emitter = new ServiceEmitter(PropUtils.getProperty(props, "druid.service"),
            PropUtils.getProperty(props, "druid.host"),
            Emitters.create(props, httpClient, jsonMapper, lifecycle));
    EmittingLogger.registerEmitter(emitter);

    final ScheduledExecutorFactory scheduledExecutorFactory = ScheduledExecutors.createFactory(lifecycle);

    final ServiceDiscoveryConfig serviceDiscoveryConfig = configFactory.build(ServiceDiscoveryConfig.class);
    CuratorFramework serviceDiscoveryCuratorFramework = Initialization
            .makeCuratorFramework(serviceDiscoveryConfig, lifecycle);
    final CuratorConfig curatorConfig = configFactory.build(CuratorConfig.class);
    CuratorFramework curatorFramework = Initialization.makeCuratorFramework(curatorConfig, lifecycle);

    final ZkPathsConfig zkPaths = configFactory.build(ZkPathsConfig.class);

    final ExecutorService exec = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ServerInventoryView-%s").build());

    final ServerInventoryViewConfig serverInventoryViewConfig = configFactory
            .build(ServerInventoryViewConfig.class);
    final String announcerType = serverInventoryViewConfig.getAnnouncerType();

    final ServerInventoryView serverInventoryView;
    if ("legacy".equalsIgnoreCase(announcerType)) {
        serverInventoryView = new SingleServerInventoryView(serverInventoryViewConfig, zkPaths,
                curatorFramework, exec, jsonMapper);
    } else if ("batch".equalsIgnoreCase(announcerType)) {
        serverInventoryView = new BatchServerInventoryView(serverInventoryViewConfig, zkPaths, curatorFramework,
                exec, jsonMapper);
    } else {
        throw new IAE("Unknown type %s", announcerType);
    }

    lifecycle.addManagedInstance(serverInventoryView);

    final DbConnectorConfig dbConnectorConfig = configFactory.build(DbConnectorConfig.class);
    final DatabaseRuleManagerConfig databaseRuleManagerConfig = configFactory
            .build(DatabaseRuleManagerConfig.class);
    final DBI dbi = new DbConnector(dbConnectorConfig).getDBI();
    DbConnector.createSegmentTable(dbi, PropUtils.getProperty(props, "druid.database.segmentTable"));
    DbConnector.createRuleTable(dbi, PropUtils.getProperty(props, "druid.database.ruleTable"));
    DatabaseRuleManager.createDefaultRule(dbi, databaseRuleManagerConfig.getRuleTable(),
            databaseRuleManagerConfig.getDefaultDatasource(), jsonMapper);

    final DatabaseSegmentManager databaseSegmentManager = new DatabaseSegmentManager(jsonMapper,
            scheduledExecutorFactory.create(1, "DatabaseSegmentManager-Exec--%d"),
            configFactory.build(DatabaseSegmentManagerConfig.class), dbi);
    final DatabaseRuleManager databaseRuleManager = new DatabaseRuleManager(jsonMapper,
            scheduledExecutorFactory.create(1, "DatabaseRuleManager-Exec--%d"), databaseRuleManagerConfig, dbi);

    final ScheduledExecutorService globalScheduledExec = scheduledExecutorFactory.create(1, "Global--%d");
    final List<Monitor> monitors = Lists.newArrayList();
    monitors.add(new JvmMonitor());
    if (Boolean.parseBoolean(props.getProperty("druid.monitoring.monitorSystem", "false"))) {
        monitors.add(new SysMonitor());
    }

    final MonitorScheduler healthMonitor = new MonitorScheduler(
            configFactory.build(MonitorSchedulerConfig.class), globalScheduledExec, emitter, monitors);
    lifecycle.addManagedInstance(healthMonitor);

    final DruidMasterConfig druidMasterConfig = configFactory.build(DruidMasterConfig.class);

    final ServiceDiscovery serviceDiscovery = Initialization
            .makeServiceDiscoveryClient(serviceDiscoveryCuratorFramework, serviceDiscoveryConfig, lifecycle);
    final ServiceAnnouncer serviceAnnouncer = Initialization.makeServiceAnnouncer(serviceDiscoveryConfig,
            serviceDiscovery);
    Initialization.announceDefaultService(serviceDiscoveryConfig, serviceAnnouncer, lifecycle);

    ServiceProvider serviceProvider = null;
    if (druidMasterConfig.getMergerServiceName() != null) {
        serviceProvider = Initialization.makeServiceProvider(druidMasterConfig.getMergerServiceName(),
                serviceDiscovery, lifecycle);
    }
    IndexingServiceClient indexingServiceClient = new IndexingServiceClient(httpClient, jsonMapper,
            serviceProvider);

    final ConfigManagerConfig configManagerConfig = configFactory.build(ConfigManagerConfig.class);
    DbConnector.createConfigTable(dbi, configManagerConfig.getConfigTable());
    JacksonConfigManager configManager = new JacksonConfigManager(new ConfigManager(dbi, configManagerConfig),
            jsonMapper);

    final LoadQueueTaskMaster taskMaster = new LoadQueueTaskMaster(curatorFramework, jsonMapper,
            scheduledExecutorFactory.create(1, "Master-PeonExec--%d"), druidMasterConfig);

    final DruidMaster master = new DruidMaster(druidMasterConfig, zkPaths, configManager,
            databaseSegmentManager, serverInventoryView, databaseRuleManager, curatorFramework, emitter,
            scheduledExecutorFactory, indexingServiceClient, taskMaster);
    lifecycle.addManagedInstance(master);

    try {
        lifecycle.start();
    } catch (Throwable t) {
        log.error(t, "Error when starting up.  Failing.");
        System.exit(1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            log.info("Running shutdown hook");
            lifecycle.stop();
        }
    }));

    final Injector injector = Guice
            .createInjector(new MasterServletModule(serverInventoryView, databaseSegmentManager,
                    databaseRuleManager, master, jsonMapper, indexingServiceClient, configManager));

    final Server server = Initialization.makeJettyServer(configFactory.build(ServerConfig.class));

    final RedirectInfo redirectInfo = new RedirectInfo() {
        @Override
        public boolean doLocal() {
            return master.isClusterMaster();
        }

        @Override
        public URL getRedirectURL(String queryString, String requestURI) {
            try {
                final String currentMaster = master.getCurrentMaster();
                if (currentMaster == null) {
                    return null;
                }

                String location = String.format("http://%s%s", currentMaster, requestURI);

                if (queryString != null) {
                    location = String.format("%s?%s", location, queryString);
                }

                return new URL(location);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };

    final Context staticContext = new Context(server, "/static", Context.SESSIONS);
    staticContext.addServlet(new ServletHolder(new RedirectServlet(redirectInfo)), "/*");

    staticContext.setResourceBase(ComputeMain.class.getClassLoader().getResource("static").toExternalForm());

    final Context root = new Context(server, "/", Context.SESSIONS);
    root.addServlet(new ServletHolder(new StatusServlet()), "/status");
    root.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    root.addEventListener(new GuiceServletConfig(injector));
    root.addFilter(GzipFilter.class, "/*", 0);
    root.addFilter(
            new FilterHolder(new RedirectFilter(new ToStringResponseHandler(Charsets.UTF_8), redirectInfo)),
            "/*", 0);
    root.addFilter(GuiceFilter.class, "/info/*", 0);
    root.addFilter(GuiceFilter.class, "/master/*", 0);

    server.start();
    server.join();
}