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.arpnetworking.clusteraggregator.configuration.ConfigurableActorProxy.java

private void swapActor() {
    LOGGER.trace().setMessage("Received a swap actor message").addContext("actor", self()).log();
    // The old actor should be stopped already, create the new ref and set it
    final Props props = _factory.create(_pendingConfiguration.get());
    final ActorRef newRef = context().actorOf(props);
    context().watch(newRef);/*from w ww  .ja  v  a 2s. c  o  m*/
    LOGGER.debug().setMessage("Started new actor due to configuration change").addData("newActor", newRef)
            .addContext("actor", self()).log();
    final ConfigurableActorStarted actorStartedNotification = new ConfigurableActorStarted(newRef);
    _observers.forEach(o -> o.tell(actorStartedNotification, self()));

    _currentChild = Optional.of(newRef);
    _pendingConfiguration = Optional.absent();
    _state = Service.State.RUNNING;
    while (!_messageBuffer.isEmpty()) {
        final BufferedMessage entry = _messageBuffer.remove();
        newRef.tell(entry.getMessage(), entry.getSender());
    }
}

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

private void listenDriveState(FlowletRuntimeService driver) {
    driver.addListener(new ServiceListenerAdapter() {
        @Override/*from  w  w  w  .j  a va  2 s  .com*/
        public void running() {
            started();
        }

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

        @Override
        public void terminated(Service.State from) {
            if (getState() != State.STOPPING) {
                LOG.warn("Flowlet terminated by itself");
                // Close all consumers
                for (ConsumerSupplier consumerSupplier : consumerSuppliers) {
                    Closeables.closeQuietly(consumerSupplier);
                }
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:cryptwallet.Main.java

private void realStart(Stage mainWindow) throws IOException {
    this.mainWindow = mainWindow;
    instance = this;
    // Show the crash dialog for any exceptions that we don't handle and that hit the main loop.
    GuiUtils.handleCrashesOnThisThread();

    if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        // We could match the Mac Aqua style here, except that (a) Modena doesn't look that bad, and (b)
        // the date picker widget is kinda broken in AquaFx and I can't be bothered fixing it.
        // AquaFx.style();
    }//from  w ww. ja v a  2  s.com

    // Load the GUI. The MainController class will be automagically created and wired up.
    URL location = getClass().getResource("main.fxml");
    FXMLLoader loader = new FXMLLoader(location);
    mainUI = loader.load();
    controller = loader.getController();
    // Configure the window with a StackPane so we can overlay things on top of the main UI, and a
    // NotificationBarPane so we can slide messages and progress bars in from the bottom. Note that
    // ordering of the construction and connection matters here, otherwise we get (harmless) CSS error
    // spew to the logs.
    notificationBar = new NotificationBarPane(mainUI);
    mainWindow.setTitle(APP_NAME);
    uiStack = new StackPane();
    Scene scene = new Scene(uiStack);
    TextFieldValidator.configureScene(scene); // Add CSS that we need.
    scene.getStylesheets().add(getClass().getResource("crypt.css").toString());
    uiStack.getChildren().add(notificationBar);
    mainWindow.setScene(scene);

    // Make log output concise.
    BriefLogFormatter.init();
    // Tell bitcoinj to run event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.
    Threading.USER_THREAD = Platform::runLater;
    // Create the app kit. It won't do any heavyweight initialization until after we start it.
    setupWalletKit(null);

    if (bitcoin.isChainFileLocked()) {
        informationalAlert("Already running",
                "This application is already running and cannot be started twice.");
        Platform.exit();
        return;
    }

    mainWindow.show();

    CryptSetPasswordController.estimateKeyDerivationTimeMsec();

    bitcoin.addListener(new Service.Listener() {
        @Override
        public void failed(Service.State from, Throwable failure) {
            GuiUtils.crashAlert(failure);
        }
    }, Platform::runLater);
    bitcoin.startAsync();

    scene.getAccelerators().put(KeyCombination.valueOf("Shortcut+F"),
            () -> bitcoin.peerGroup().getDownloadPeer().close());
}

From source file:org.invenzzia.helium.gui.ContextManagerService.java

@Subscribe
public void notifyContextStateChanged(ContextStateChangeEvent event) {
    if (event.getState() == Service.State.STOPPING) {
        if (this.isTerminating) {
            return;
        }/*from w ww.  j  av  a  2 s. c o m*/
        // Before we let terminating the context that spawned
        // this event, we must stop all the upper contexts first.
        AbstractContext ctx = event.getContext();

        while (this.contexts.peek() != ctx) {
            this.popContext();
        }
    }
}

From source file:com.mycelium.Main.java

private void realStart(Stage mainWindow) throws IOException {
    this.mainWindow = mainWindow;
    instance = this;
    // Show the crash dialog for any exceptions that we don't handle and that hit the main loop.
    GuiUtils.handleCrashesOnThisThread();

    if (System.getProperty("os.name").toLowerCase().contains("mac")) {
        // We could match the Mac Aqua style here, except that (a) Modena doesn't look that bad, and (b)
        // the date picker widget is kinda broken in AquaFx and I can't be bothered fixing it.
        // AquaFx.style();
    }/*  w  ww. ja v  a 2 s . c o  m*/

    // Load the GUI. The MainController class will be automagically created and wired up.
    URL location = getClass().getResource("main.fxml");
    FXMLLoader loader = new FXMLLoader(location);
    mainUI = loader.load();
    controller = loader.getController();
    // Configure the window with a StackPane so we can overlay things on top of the main UI, and a
    // NotificationBarPane so we can slide messages and progress bars in from the bottom. Note that
    // ordering of the construction and connection matters here, otherwise we get (harmless) CSS error
    // spew to the logs.
    notificationBar = new NotificationBarPane(mainUI);
    mainWindow.setTitle(APP_NAME);
    uiStack = new StackPane();
    Scene scene = new Scene(uiStack);
    TextFieldValidator.configureScene(scene); // Add CSS that we need.
    scene.getStylesheets().add(getClass().getResource("wallet.css").toString());
    uiStack.getChildren().add(notificationBar);
    mainWindow.setScene(scene);

    // Make log output concise.
    BriefLogFormatter.init();
    // Tell bitcoinj to run event handlers on the JavaFX UI thread. This keeps things simple and means
    // we cannot forget to switch threads when adding event handlers. Unfortunately, the DownloadListener
    // we give to the app kit is currently an exception and runs on a library thread. It'll get fixed in
    // a future version.
    Threading.USER_THREAD = Platform::runLater;
    // Create the app kit. It won't do any heavyweight initialization until after we start it.
    setupWalletKit(null);
    if (bitcoin.isChainFileLocked()) {
        informationalAlert("Already running",
                "This application is already running and cannot be started twice.");
        Platform.exit();
        return;
    }

    mainWindow.show();

    WalletSetPasswordController.estimateKeyDerivationTimeMsec();

    bitcoin.addListener(new Service.Listener() {
        @Override
        public void failed(Service.State from, Throwable failure) {
            GuiUtils.crashAlert(failure);
        }
    }, Platform::runLater);

    bitcoin.startAsync();

    scene.getAccelerators().put(KeyCombination.valueOf("Shortcut+F"),
            () -> bitcoin.peerGroup().getDownloadPeer().close());
}

From source file:com.technostar98.tcbot.bot.BotManager.java

public static void stop() {
    synchronized (lock) {
        try {// ww w .ja  v  a 2  s .  c  o m
            dataManager.interrupt();
            while (dataManager.getState() != Thread.State.TIMED_WAITING) {
            }

            manager.servicesByState().entries().parallelStream()
                    .filter(e -> e.getKey() == Service.State.RUNNING).forEach(e -> e.getValue().stopAsync());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //TODO close anything else necessary
        dataManager.interrupt();
        forceDebuggerShutdown();
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.arpnetworking.clusteraggregator.configuration.ConfigurableActorProxy.java

private void applyConfiguration(final ApplyConfiguration<T> applyConfiguration) {
    LOGGER.trace().setMessage("Received an apply configuration message")
            .addData("configuration", applyConfiguration.getConfiguration()).addContext("actor", self()).log();
    _pendingConfiguration = Optional.of(applyConfiguration.getConfiguration());
    // Tear down the old actor
    if (_currentChild.isPresent() && _state.equals(Service.State.RUNNING)) {
        _state = Service.State.STOPPING;
        final ActorRef toStop = _currentChild.get();
        toStop.tell(PoisonPill.getInstance(), self());
        LOGGER.info().setMessage("Requested current actor to shutdown for swap").addData("currentActor", toStop)
                .addContext("actor", self()).log();
    } else if (_state.equals(Service.State.NEW)) {
        LOGGER.info().setMessage("Applying initial configuration, no current actor to shutdown")
                .addContext("actor", self()).log();
        self().tell(new SwapActor(), self());
    }/*w  w w.j a v  a2 s.co  m*/
}

From source file:org.libdohj.cate.Network.java

/**
 * @param context context this network manages.
 * @param controller the controller to push events back to.
 * @param directory the data directory to store the wallet and SPV chain in.
 * @param networkExecutor executor for tasks belonging to this network.
 * Must exist after the lifecycle of network (so that service status listeners
 * can be attached to it)./*from w  ww .jav  a 2 s  . c  o  m*/
 */
public Network(final Context context, final MainController controller, final File directory,
        final Executor networkExecutor, final BiConsumer<Network, Wallet> registerWalletHook) {
    super(context, directory, "cate_" + context.getParams().getId());
    this.controller = controller;
    this.networkExecutor = networkExecutor;
    autoStop = false;
    blockingStartup = true;
    this.registerWalletHook = registerWalletHook;

    monetaryFormatter = context.getParams().getMonetaryFormat();
    addListener(new Service.Listener() {
        @Override
        public void running() {
            estimatedBalance.set(
                    monetaryFormatter.format(wallet().getBalance(Wallet.BalanceType.ESTIMATED)).toString());
            try {
                blocks.set(store().getChainHead().getHeight());
            } catch (BlockStoreException ex) {
                logger.error("Error getting current chain head while starting wallet " + params.getId(), ex);
            }
            encrypted.set(wallet().isEncrypted());
        }

        @Override
        public void failed(Service.State from, Throwable failure) {
            controller.onNetworkFailed(Network.this, from, failure);
        }
    }, networkExecutor);
}

From source file:com.griddynamics.jagger.engine.e1.process.WorkloadProcess.java

public void changeConfiguration(WorkloadConfiguration configuration) {
    log.debug("Configuration change request received");

    for (Iterator<WorkloadService> it = threads.iterator(); it.hasNext();) {
        WorkloadService workloadService = it.next();
        if (workloadService.state().equals(Service.State.TERMINATED)) {
            samplesCountStartedFromTerminatedThreads += workloadService.getStartedSamples();
            samplesCountFinishedFromTerminatedThreads += workloadService.getFinishedSamples();
            it.remove();//from  w ww  .  java 2s . c o m
        }
    }

    final int threadDiff = configuration.getThreads() - threads.size();

    if (threadDiff < 0) {
        log.debug("Going to decrease thread count by {}", threadDiff);
        removeThreads(Math.abs(threadDiff));
    }

    if (totalSamplesCountRequested != configuration.getSamples()) {
        leftSamplesCount.addAndGet(configuration.getSamples() - totalSamplesCountRequested);
        totalSamplesCountRequested = configuration.getSamples();
    }

    if (threadDiff > 0 && (!predefinedSamplesCount() || leftSamplesCount.get() > 0)) {
        log.debug("Going to increase thread count by {}", threadDiff);
        for (int i = threadDiff; i > 0; i--) {
            addThread();
        }
    }

    delay = configuration.getDelay();
    log.debug("Delay should be changed to {}", delay);
    for (WorkloadService thread : threads) {
        thread.changeDelay(delay);
    }
}

From source file:com.google.cloud.pubsub.spi.v1.Subscriber.java

public void addListener(final SubscriberListener listener, Executor executor) {
    impl.addListener(new Service.Listener() {
        @Override//from  w  w  w  .  j  a  v a  2  s  .c  o  m
        public void failed(Service.State from, Throwable failure) {
            listener.failed(convertState(from), failure);
        }

        @Override
        public void running() {
            listener.running();
        }

        @Override
        public void starting() {
            listener.starting();
        }

        @Override
        public void stopping(Service.State from) {
            listener.stopping(convertState(from));
        }

        @Override
        public void terminated(Service.State from) {
            listener.terminated(convertState(from));
        }
    }, executor);
}