Example usage for com.google.common.util.concurrent Service startAsync

List of usage examples for com.google.common.util.concurrent Service startAsync

Introduction

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

Prototype

Service startAsync();

Source Link

Document

If the service state is State#NEW , this initiates service startup and returns immediately.

Usage

From source file:com.torodb.standalone.Main.java

public static void main(String[] args) throws Exception {
    Console console = JCommander.getConsole();

    ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
    final CliConfig cliConfig = new CliConfig();
    JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
    jCommander.setColumnSize(Integer.MAX_VALUE);

    if (cliConfig.isHelp()) {
        jCommander.usage();/*from w w w.jav  a  2 s  .  c  om*/
        System.exit(0);
    }

    if (cliConfig.isHelpParam()) {
        console.println(cliBundle.getString("help-param-header"));
        ResourceBundle configBundle = PropertyResourceBundle.getBundle("ConfigMessages");
        ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, configBundle, console, 0);
        System.exit(0);
    }

    final Config config = CliConfigUtils.readConfig(cliConfig);

    if (cliConfig.isPrintConfig()) {
        ConfigUtils.printYamlConfig(config, console);

        System.exit(0);
    }

    if (cliConfig.isPrintXmlConfig()) {
        ConfigUtils.printXmlConfig(config, console);

        System.exit(0);
    }

    configureLogger(cliConfig, config);

    config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
        @Override
        public void visit(AbstractDerby value) {
            parseToropassFile(value);
        }

        @Override
        public void visit(AbstractPostgres value) {
            parseToropassFile(value);
        }

        public void parseToropassFile(BackendPasswordConfig value) {
            try {
                ConfigUtils.parseToropassFile(value);
            } catch (Exception ex) {
                throw new SystemException(ex);
            }
        }
    });
    if (config.getProtocol().getMongo().getReplication() != null) {
        for (AbstractReplication replication : config.getProtocol().getMongo().getReplication()) {
            if (replication.getAuth().getUser() != null) {
                HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource())
                        .withDefaultPort(27017);
                ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                    @Override
                    public void setPassword(String password) {
                        replication.getAuth().setPassword(password);
                    }

                    @Override
                    public String getUser() {
                        return replication.getAuth().getUser();
                    }

                    @Override
                    public Integer getPort() {
                        return syncSource.getPort();
                    }

                    @Override
                    public String getPassword() {
                        return replication.getAuth().getPassword();
                    }

                    @Override
                    public String getMongopassFile() {
                        return config.getProtocol().getMongo().getMongopassFile();
                    }

                    @Override
                    public String getHost() {
                        return syncSource.getHostText();
                    }

                    @Override
                    public String getDatabase() {
                        return replication.getAuth().getSource();
                    }
                });
            }
        }
    }

    if (config.getBackend().isLike(AbstractPostgres.class)) {
        AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + postgres.getUser() + " password:");
            postgres.setPassword(readPwd());
        }
    } else if (config.getBackend().isLike(AbstractDerby.class)) {
        AbstractDerby derby = config.getBackend().as(AbstractDerby.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + derby.getUser() + " password:");
            derby.setPassword(readPwd());
        }
    }

    try {
        Clock clock = Clock.systemDefaultZone();
        Service server;
        if (config.getProtocol().getMongo().getReplication() == null
                || config.getProtocol().getMongo().getReplication().isEmpty()) {
            Service toroDbServer = ToroDbBootstrap.createStandaloneService(config, clock);

            toroDbServer.startAsync();
            toroDbServer.awaitRunning();

            server = toroDbServer;
        } else {
            throw new UnsupportedOperationException("Replication not supported yet!");
        }

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            server.stopAsync();
            server.awaitTerminated();
        }));
    } catch (CreationException ex) {
        ex.getErrorMessages().stream().forEach(m -> {
            if (m.getCause() != null) {
                LOGGER.error(m.getCause().getMessage());
            } else {
                LOGGER.error(m.getMessage());
            }
        });
        System.exit(1);
    } catch (Throwable ex) {
        LOGGER.error("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:com.torodb.stampede.Main.java

public static void main(String[] args) throws Exception {
    try {/*w ww.j a v a 2 s.co  m*/
        Console console = JCommander.getConsole();

        ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
        final CliConfig cliConfig = new CliConfig();
        JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
        jCommander.setColumnSize(Integer.MAX_VALUE);

        if (cliConfig.isVersion()) {
            BuildProperties buildProperties = new DefaultBuildProperties();
            console.println(buildProperties.getFullVersion());
            System.exit(0);
        }

        if (cliConfig.isHelp()) {
            jCommander.usage();
            System.exit(0);
        }

        if (cliConfig.isHelpParam()) {
            console.println(cliBundle.getString("cli.help-param-header"));
            ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, cliBundle, console, 0);
            System.exit(0);
        }

        cliConfig.addParams();

        final Config config = CliConfigUtils.readConfig(cliConfig);

        if (cliConfig.isPrintConfig()) {
            ConfigUtils.printYamlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintXmlConfig()) {
            ConfigUtils.printXmlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintParam()) {
            JsonNode jsonNode = ConfigUtils.getParam(config, cliConfig.getPrintParamPath());

            if (jsonNode != null) {
                console.print(jsonNode.asText());
            }

            System.exit(0);
        }

        configureLogger(cliConfig, config);

        config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
            @Override
            public void visit(AbstractDerby value) {
                parseToropassFile(value);
            }

            @Override
            public void visit(AbstractPostgres value) {
                parseToropassFile(value);
            }

            public void parseToropassFile(BackendPasswordConfig value) {
                try {
                    ConfigUtils.parseToropassFile(value);
                } catch (Exception ex) {
                    throw new SystemException(ex);
                }
            }
        });
        AbstractReplication replication = config.getReplication();
        if (replication.getAuth().getUser() != null) {
            HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
            ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                @Override
                public void setPassword(String password) {
                    replication.getAuth().setPassword(password);
                }

                @Override
                public String getUser() {
                    return replication.getAuth().getUser();
                }

                @Override
                public Integer getPort() {
                    return syncSource.getPort();
                }

                @Override
                public String getPassword() {
                    return replication.getAuth().getPassword();
                }

                @Override
                public String getMongopassFile() {
                    return config.getReplication().getMongopassFile();
                }

                @Override
                public String getHost() {
                    return syncSource.getHostText();
                }

                @Override
                public String getDatabase() {
                    return replication.getAuth().getSource();
                }
            });
        }

        if (config.getBackend().isLike(AbstractPostgres.class)) {
            AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

            if (cliConfig.isAskForPassword()) {
                console.print("Type database user " + postgres.getUser() + "'s password:");
                postgres.setPassword(readPwd());
            }

            if (postgres.getPassword() == null) {
                throw new SystemException("No password provided for database user " + postgres.getUser()
                        + ".\n\n" + "Please add following line to file " + postgres.getToropassFile() + ":\n"
                        + postgres.getHost() + ":" + postgres.getPort() + ":" + postgres.getDatabase() + ":"
                        + postgres.getUser() + ":<password>\n" + "Replace <password> for database user "
                        + postgres.getUser() + "'s password");
            }
        }

        try {
            Clock clock = Clock.systemDefaultZone();

            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "Since is really hard to stop cleanly all threads when an OOME is thrown we must "
                        + "exit to avoid no more action is performed that could lead to an unespected "
                        + "state")
                public void uncaughtException(Thread t, Throwable e) {
                    if (e instanceof OutOfMemoryError) {
                        try {
                            LOGGER.error("Fatal out of memory: " + e.getLocalizedMessage(), e);
                        } finally {
                            System.exit(1);
                        }
                    }
                }
            });

            Service stampedeService = StampedeBootstrap.createStampedeService(config, clock);

            stampedeService.startAsync();
            stampedeService.awaitTerminated();

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                stampedeService.stopAsync();
                stampedeService.awaitTerminated();
            }));
        } catch (CreationException ex) {
            ex.getErrorMessages().stream().forEach(m -> {
                if (m.getCause() != null) {
                    LOGGER.error(m.getCause().getMessage());
                } else {
                    LOGGER.error(m.getMessage());
                }
            });
            LogManager.shutdown();
            System.exit(1);
        }
    } catch (Throwable ex) {
        LOGGER.debug("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        LogManager.shutdown();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:org.apache.aurora.scheduler.state.PubsubTestUtil.java

/**
 * Starts the pubsub system and gets a handle to the event sink where pubsub events may be sent.
 *
 * @param injector Injector where the pubsub system was installed.
 * @return The pubsub event sink./*  ww w.  j  a v a 2  s  . co  m*/
 * @throws Exception If the pubsub system failed to start.
 */
public static EventSink startPubsub(Injector injector) throws Exception {
    // TODO(wfarner): Make it easier to write a unit test wired for pubsub events.
    // In this case, a trade-off was made to avoid installing several distant modules and providing
    // required bindings that seem unrelated from this code.
    Set<Service> services = injector.getInstance(Key.get(new TypeLiteral<Set<Service>>() {
    }, AppStartup.class));

    for (Service service : services) {
        service.startAsync().awaitRunning();
    }
    return injector.getInstance(EventSink.class);
}

From source file:co.runrightfast.core.utils.ServiceUtils.java

static void start(@NonNull final Service service) {
    switch (service.state()) {
    case NEW:/*  w w  w. j a  v  a 2  s  .  co m*/
        service.startAsync();
        awaitRunning(service);
        return;
    case STARTING:
        service.awaitRunning();
        awaitRunning(service);
        return;
    case RUNNING:
        return;
    default:
        throw new IllegalStateException(
                "Service cannot be started because the service state is :" + service.state());
    }

}

From source file:co.runrightfast.commons.utils.ServiceUtils.java

public static void start(@NonNull final Service service) {
    switch (service.state()) {
    case NEW:/*from  w w  w .  j a v a2s .  co m*/
        service.startAsync();
        awaitRunning(service);
        return;
    case STARTING:
        service.awaitRunning();
        awaitRunning(service);
        return;
    case RUNNING:
        return;
    default:
        throw new IllegalServiceStateTransitionException(service.state(), RUNNING);
    }

}

From source file:io.pravega.common.concurrent.ServiceHelpers.java

/**
 * Asynchronously starts a Service and returns a CompletableFuture that will indicate when it is running.
 *
 * @param service  The Service to start.
 * @param executor An Executor to use for callback invocations.
 * @return A CompletableFuture that will be completed when the service enters a RUNNING state, or completed
 * exceptionally if the service failed to start.
 *//*from  www .  ja va 2 s  .c om*/
public static CompletableFuture<Void> startAsync(Service service, Executor executor) {
    // Service.startAsync() will fail if the service is not in a NEW state. That is, if it is already RUNNING or
    // STARTED, then the method will fail synchronously, hence we are not in danger of not invoking our callbacks,
    // as long as we register the Listener before we attempt to start.
    // Nevertheless, do make a sanity check since once added, a Listener cannot be removed.
    Preconditions.checkState(service.state() == Service.State.NEW, "Service expected to be %s but was %s.",
            Service.State.NEW, service.state());
    Preconditions.checkNotNull(executor, "executor");
    CompletableFuture<Void> result = new CompletableFuture<>();
    service.addListener(new StartupListener(result), executor);
    service.startAsync();
    return result;
}

From source file:com.torodb.core.bundle.DependenciesBundle.java

@Override
protected void postDependenciesStartUp() throws Exception {
    for (Service managedDependency : getManagedDependencies()) {
        managedDependency.startAsync();
        managedDependency.awaitRunning();
    }/*  www  .  j ava2s. co m*/
}

From source file:flipkart.mongo.replicator.cluster.ClusterReplicator.java

@Override
protected void doStart() {

    Set<Service> replicaSetServices = new LinkedHashSet<Service>();
    for (ReplicaSetConfig rsConfig : cluster.getReplicaSets()) {
        replicaSetServices.add(new ReplicaSetReplicator(taskContext, rsConfig));
    }//from   ww  w  .jav  a 2 s  .com

    /**
     * getting set of replicaSetReplicators for defined replicas and
     * attaching them to serviceManager for starting and stopping
     */
    replicasReplicatorServiceManager = new ServiceManager(replicaSetServices);
    replicasReplicatorServiceManager.addListener(new ServiceManager.Listener() {
        @Override
        public void healthy() {

        }

        @Override
        public void stopped() {

        }

        @Override
        public void failure(Service service) {
            service.startAsync();
        }
    });

    replicasReplicatorServiceManager.startAsync();
}

From source file:com.torodb.stampede.StampedeService.java

private void startBundle(Service service) {
    service.startAsync();
    service.awaitRunning();

    shutdowner.addStopShutdownListener(service);
}

From source file:org.icgc.dcc.submission.core.DccRuntime.java

private void tryStartService(Service service) {
    try {/*from  ww  w  . j  a v a2 s. c o  m*/
        log.info("Service {} is [{}]. Starting.", service.getClass(), service.state());
        service.startAsync().awaitRunning();

        val expectedState = RUNNING;
        val actualState = service.state();
        checkState(expectedState == actualState, "Service should be '%s', instead was found '%s'",
                expectedState, actualState);

        log.info("Service {} is now [{}]", service.getClass(), actualState);
    } catch (UncheckedExecutionException e) {
        log.warn("Failed to start service {}: {}", service.getClass(), e.getCause().getMessage());
        throw e;
    }
}