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

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

Introduction

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

Prototype

State state();

Source Link

Document

Returns the lifecycle state of the service.

Usage

From source file:com.googlecode.blaisemath.graph.layout.IterativeGraphLayoutService.java

IterativeGraphLayoutService(IterativeGraphLayoutManager mgr, int loopDelay) {
    this.manager = mgr;
    this.loopDelay = loopDelay;
    addListener(new Listener() {
        @Override/*w w w  . java2  s .c om*/
        public void failed(Service.State from, Throwable failure) {
            LOG.log(Level.SEVERE, "Layout service failed", failure);
        }
    }, MoreExecutors.sameThreadExecutor());
}

From source file:com.continuuity.weave.internal.ListenerExecutor.java

@Override
public void running() {
    if (hasCalled(Service.State.RUNNING)) {
        return;//ww w .  j  a  va  2  s .c  om
    }
    executor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                delegate.running();
            } catch (Throwable t) {
                LOG.warn("Exception thrown from listener", t);
            }
        }
    });
}

From source file:c5db.SimpleC5ModuleListener.java

@Override
public void terminated(Service.State from) {
    logger.info("Terminated module {}", module);
    onStoppingModule.run();
}

From source file:org.asoem.greyfish.cli.GreyfishCLIApplication.java

public static void main(final String[] args) {

    final Optional<String> commitHash = getCommitHash(GreyfishCLIApplication.class);
    if (commitHash.isPresent()) {
        logger.debug("Git Commit Hash for current Jar: %s", commitHash.get());
    }/*from  ww w .j  a  v a 2s.c om*/

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                closer.close();
            } catch (IOException e) {
                logger.warn("Exception while closing resources", e);
            }
        }
    });

    try {
        final OptionSet optionSet = optionParser.parse(args);

        if (optionSet.has(helpOptionSpec)) {
            printHelp();
            System.exit(0);
        }

        final Module commandLineModule = createCommandLineModule(optionSet);
        final RandomGenerator randomGenerator = RandomGenerators
                .threadLocalGenerator(new Supplier<RandomGenerator>() {
                    @Override
                    public RandomGenerator get() {
                        return new Well19937c();
                    }
                });
        final EventBus eventBus = new EventBus(new SubscriberExceptionHandler() {
            @Override
            public void handleException(final Throwable exception, final SubscriberExceptionContext context) {
                context.getEventBus()
                        .post(new AssertionError("The EventBus could not dispatch event: "
                                + context.getSubscriber() + " to " + context.getSubscriberMethod(),
                                exception.getCause()));
            }
        });
        final Module coreModule = new CoreModule(randomGenerator, eventBus);

        final Injector injector = Guice.createInjector(coreModule, commandLineModule);

        final ExperimentExecutionService experimentExecutionService = injector
                .getInstance(ExperimentExecutionService.class);

        if (!optionSet.has(quietOptionSpec)) {
            final ExperimentMonitorService monitorService = new ExperimentMonitorService(System.out, eventBus);

            monitorService.addListener(new Service.Listener() {
                @Override
                public void starting() {
                }

                @Override
                public void running() {
                }

                @Override
                public void stopping(final Service.State from) {
                }

                @Override
                public void terminated(final Service.State from) {
                }

                @Override
                public void failed(final Service.State from, final Throwable failure) {
                    logger.error("Monitor service failed", failure);
                }
            }, MoreExecutors.sameThreadExecutor());

            experimentExecutionService.addListener(new MonitorServiceController(monitorService),
                    MoreExecutors.sameThreadExecutor());
        }

        // start getSimulation
        experimentExecutionService.startAsync();

        // stop getSimulation on shutdown request (^C)
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (experimentExecutionService.isRunning()) {
                    experimentExecutionService.stopAsync().awaitTerminated();
                }
            }
        });

        try {
            experimentExecutionService.awaitTerminated();
        } catch (IllegalStateException e) {
            exitWithErrorMessage("Simulation execution failed", e);
        }
    } catch (OptionException e) {
        exitWithErrorMessage("Failed parsing options: ", e, true);
    } catch (Throwable e) {
        exitWithErrorMessage(String.format(
                "Exception during simulation execution: %s\n" + "Check log file for a stack trace.",
                e.getCause() != null ? e.getCause().getMessage() : e.getMessage()), e);
    }

    System.exit(0);
}

From source file:c5db.SimpleModuleInformationProvider.java

public ListenableFuture<Service.State> startModule(C5Module module) {
    SettableFuture<Service.State> startedFuture = SettableFuture.create();
    Service.Listener stateChangeListener = new SimpleC5ModuleListener(module, () -> {
        addRunningModule(module);// ww w .  j a  v  a 2  s .co m
        startedFuture.set(null);
    }, () -> removeModule(module), failureHandler);

    module.addListener(stateChangeListener, fiber);
    modules.put(module.getModuleType(), module);
    module.start();

    return startedFuture;
}

From source file:co.cask.cdap.internal.app.runtime.ProgramControllerServiceAdapter.java

private void listenToRuntimeState(Service service) {
    service.addListener(new ServiceListenerAdapter() {
        @Override//from  ww w.j  ava  2s .c  om
        public void running() {
            started();
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            LOG.error("Program terminated with exception", failure);
            error(failure);
        }

        @Override
        public void terminated(Service.State from) {
            if (from != Service.State.STOPPING) {
                // Service completed by itself. Simply signal the state change of this controller.
                complete();
            } else {
                // Service was killed
                stop();
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:c5db.SimpleC5ModuleListener.java

@Override
public void failed(Service.State from, Throwable failure) {
    logger.error("Failed module {}: {}", module, failure);
    onStoppingModule.run();//from  w  w  w. ja  va  2s  .  c  o m
    throwableConsumer.accept(failure);
}

From source file:com.continuuity.weave.internal.ServiceMain.java

protected final void doMain(final Service service) throws ExecutionException, InterruptedException {
    configureLogger();//from   w  w  w .j  a v  a  2  s. com

    final String serviceName = service.getClass().getName();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOG.info("Shutdown hook triggered. Shutting down service " + serviceName);
            service.stopAndWait();
            LOG.info("Service shutdown " + serviceName);
        }
    });

    // Listener for state changes of the service
    final SettableFuture<Service.State> completion = SettableFuture.create();
    service.addListener(new Service.Listener() {
        @Override
        public void starting() {
            LOG.info("Starting service " + serviceName);
        }

        @Override
        public void running() {
            LOG.info("Service running " + serviceName);
        }

        @Override
        public void stopping(Service.State from) {
            LOG.info("Stopping service " + serviceName + " from " + from);
        }

        @Override
        public void terminated(Service.State from) {
            LOG.info("Service terminated " + serviceName + " from " + from);
            completion.set(from);
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            LOG.info("Service failure " + serviceName, failure);
            completion.setException(failure);
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Starts the service
    service.start();

    try {
        // If container failed with exception, the future.get() will throws exception
        completion.get();
    } finally {
        //      ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
        //      if (loggerFactory instanceof LoggerContext) {
        //        ((LoggerContext) loggerFactory).stop();
        //      }
    }
}

From source file:com.continuuity.weave.internal.ListenerExecutor.java

@Override
public void stopping(final Service.State from) {
    if (hasCalled(Service.State.STOPPING)) {
        return;//from w w  w  .j a  va  2s .c  o  m
    }
    executor.execute(new Runnable() {
        @Override
        public void run() {
            try {
                delegate.stopping(from);
            } catch (Throwable t) {
                LOG.warn("Exception thrown from listener", t);
            }
        }
    });
}

From source file:org.graylog.collector.cli.commands.Run.java

@Override
public void run() {
    LOG.info("Starting Collector v{} (commit {})", CollectorVersion.CURRENT.version(),
            CollectorVersion.CURRENT.commitIdShort());

    showOsInfo();// w w  w .jav a  2s  . com

    final Injector injector = getInjector();
    serviceManager = injector.getInstance(CollectorServiceManager.class);

    validateConfiguration(serviceManager.getConfiguration());

    serviceManager.start();

    for (Map.Entry<Service.State, Service> entry : serviceManager.servicesByState().entries()) {
        LOG.info("Service {}: {}", entry.getKey().toString(), entry.getValue().toString());
    }

    serviceManager.awaitStopped();
}