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

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

Introduction

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

Prototype

Service stopAsync();

Source Link

Document

If the service is State#STARTING starting or State#RUNNING running , this initiates service shutdown and returns immediately.

Usage

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

public static void main(String[] args) throws Exception {
    try {/*from w  w w  .  j  av  a2 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: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();// w  w w. jav a 2s  .c o  m
        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:co.runrightfast.core.utils.ServiceUtils.java

static void stopAsync(final Service service) {
    if (service != null) {
        switch (service.state()) {
        case STARTING:
        case RUNNING:
            service.stopAsync();
            return;
        case STOPPING:
            return;
        case NEW:
        case FAILED:
        case TERMINATED:
            LOG.logp(FINE, ServiceUtils.class.getName(), "stop", () -> String
                    .format("Service (%s) is not running: %s", service.getClass().getName(), service.state()));

        }//from   w w w.j a  v a  2s. c  o m
    }
}

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

public static void stopAsync(final Service service) {
    if (service != null) {
        switch (service.state()) {
        case STARTING:
        case RUNNING:
            service.stopAsync();
            return;
        case STOPPING:
            return;
        case NEW:
        case FAILED:
        case TERMINATED:
            log.debug("Service ({}) is not running: {}", service.getClass().getName(), service.state());
        }//from   w  w w.ja  v a2 s  .c om
    }
}

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

/**
 *
 * @param service if null, then do nothing
 *///from ww  w.j a  va  2  s  .  c o m
static void stop(final Service service) {
    if (service != null) {
        switch (service.state()) {
        case STARTING:
        case RUNNING:
            service.stopAsync();
            awaitTerminated(service);
            return;
        case STOPPING:
            awaitTerminated(service);
            return;
        case NEW:
        case FAILED:
        case TERMINATED:
            LOG.logp(FINE, ServiceUtils.class.getName(), "stop", () -> String
                    .format("Service (%s) is not running: %s", service.getClass().getName(), service.state()));
        }
    }
}

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

/**
 *
 * @param service if null, then do nothing
 *//*from   www .  j  av  a  2  s.  c  om*/
public static void stop(final Service service) {
    if (service != null) {
        switch (service.state()) {
        case STARTING:
        case RUNNING:
            service.stopAsync();
            awaitTerminated(service);
            return;
        case STOPPING:
            awaitTerminated(service);
            return;
        case NEW:
        case FAILED:
        case TERMINATED:
            log.debug("Service ({}) is not running: {}", service.getClass().getName(), service.state());
        }
    }
}

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

/**
 * Asynchronously stops a Service and returns a CompletableFuture that will indicate when it is stopped.
 *
 * @param service  The Service to stop./*from  w  ww .  j  av a  2 s  . c o  m*/
 * @param executor An Executor to use for callback invocations.
 * @return A CompletableFuture that will be completed when the service enters a TERMINATED state, or completed
 * exceptionally if the service enters a FAILED state.
 */
public static CompletableFuture<Void> stopAsync(Service service, Executor executor) {
    // Service.stopAsync() will not throw any exceptions, but will transition the Service to either TERMINATED
    // or FAILED. We need to register the listener before we attempt to stop.
    CompletableFuture<Void> result = new CompletableFuture<>();
    onStop(service, () -> result.complete(null), result::completeExceptionally, executor);
    service.stopAsync();
    return result;
}

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

@Override
protected void preDependenciesShutDown() throws Exception {
    for (Service managedDependency : Lists.reverse(getManagedDependencies())) {
        managedDependency.stopAsync();
        managedDependency.awaitTerminated();
    }/* w  w  w.j  av  a2  s .  co  m*/
}

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

private void tryStopService(Service service) {
    try {//from   www.ja v  a  2 s.  c  o m
        log.info("Service {} is [{}]. Stopping.", service.getClass(), service.state());
        service.stopAsync().awaitTerminated();

        val expectedState = TERMINATED;
        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.error("Failed to stop service {}: {}", service.getClass(), e.getCause().getMessage());
        throw e;
    }
}

From source file:com.aceevo.ursus.core.UrsusNIOApplication.java

/**
 * Convenience method for starting {@link NIOTransport}
 *
 * @param transport//w  w  w . ja v  a  2  s .  c  o  m
 */
protected void startWithShutdownHook(final NIOTransport transport) {

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping Grizzly NIOTransport...");
            try {
                transport.shutdownNow();
                LOGGER.info("Stopping all managed services...");
                for (Service service : managedServices) {
                    service.stopAsync();
                }
            } catch (IOException e) {
                LOGGER.error("failed to stop transport", e);
            }
        }
    }, "shutdownHook"));

    try {
        LOGGER.info("Starting all managed services...");
        for (Service service : managedServices) {
            service.startAsync();
        }

        UrsusNIOApplicationConfiguration.Server server = configuration.getServer();
        transport.bind(server.getHost(), server.getPort());
        transport.start();
        ursusApplicationHelper.printBanner(LOGGER, getClass().getSimpleName());
        LOGGER.info("Press CTRL^C to exit..");
        Thread.currentThread().join();
    } catch (Exception e) {
        LOGGER.error("There was an error while starting Grizzly HTTP server.", e);
    }
}