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:net.bither.bitherj.core.Peer.java

public void connect() {
    if (state != State.Disconnected) {
        log.info("peer[{}:{}] call connect, but its state is not disconnected",
                this.peerAddress.getHostAddress(), this.peerPort);
        return;//from  w  w w.j  a  v a 2  s . c om
    } else {
        log.info("peer[{}:{}] call connect", this.peerAddress.getHostAddress(), this.peerPort);
        state = State.Connecting;
        if (!NioClientManager.instance().isRunning()) {
            if (NioClientManager.instance().startAndWait() != Service.State.RUNNING) {
                NioClientManager.instance().startUpError();
            }
        }
        setTimeoutEnabled(true);
        setSocketTimeout(TimeOutDelay);
        bloomFilterSent = false;
        try {
            NioClientManager.instance()
                    .openConnection(new InetSocketAddress(getPeerAddress(), BitherjSettings.port), this);
        } catch (Exception ex) {
            exceptionCaught(ex);
        }
    }
}

From source file:com.google.litecoin.kits.NewWalletAppKit.java

/**
 * If true, the wallet will save itself to disk automatically whenever
 * it changes./*from w  w  w  . ja v a 2s. c  om*/
 */
public NewWalletAppKit setAutoSave(boolean value) {
    checkState(state() == Service.State.NEW, "Cannot call after startup");
    useAutoSave = value;
    return this;
}

From source file:io.pravega.segmentstore.server.store.StreamSegmentContainerRegistry.java

private static boolean isShutdown(Service.State state) {
    return state == Service.State.FAILED || state == Service.State.STOPPING
            || state == Service.State.TERMINATED;
}

From source file:io.pravega.segmentstore.server.store.StreamSegmentContainerRegistry.java

private void unregisterContainer(ContainerWithHandle containerWithHandle) {
    assert containerWithHandle != null : "containerWithHandle is null.";
    assert containerWithHandle.container.state() == Service.State.TERMINATED
            || containerWithHandle.container.state() == Service.State.FAILED : "Container is not stopped.";

    // First, release all resources owned by this instance.
    containerWithHandle.container.close();

    // Unregister the container.
    this.containers.remove(containerWithHandle.handle.getContainerId());

    // Notify the handle that the container is now in a Stopped state.
    containerWithHandle.handle.notifyContainerStopped();
    log.info("Unregistered SegmentContainer {}.", containerWithHandle.handle.getContainerId());

    containerWithHandle.shutdownNotifier.complete(null);
}

From source file:cryptwallet.CryptSettingsController.java

public void restoreClicked(ActionEvent event) {
    // Don't allow a restore unless this wallet is presently empty. We don't want to end up with two wallets, too
    // much complexity, even though WalletAppKit will keep the current one as a backup file in case of disaster.
    if (Main.bitcoin.wallet().getBalance().value > 0) {
        informationalAlert("Wallet is not empty",
                "You must empty this wallet out before attempting to restore an older one, as mixing wallets "
                        + "together can lead to invalidated backups.");
        return;/*from   w w w . j  a v a  2 s  .  co  m*/
    }

    if (aesKey != null) {
        // This is weak. We should encrypt the new seed here.
        informationalAlert("Wallet is encrypted",
                "After restore, the wallet will no longer be encrypted and you must set a new password.");
    }

    log.info("Attempting wallet restore using seed '{}' from date {}", wordsArea.getText(),
            datePicker.getValue());
    informationalAlert("Wallet restore in progress",
            "Your wallet will now be resynced from the Bitcoin network. This can take a long time for old wallets.");
    overlayUI.done();
    Main.instance.controller.restoreFromSeedAnimation();

    long birthday = datePicker.getValue().atStartOfDay().toEpochSecond(ZoneOffset.UTC);
    DeterministicSeed seed = new DeterministicSeed(Splitter.on(' ').splitToList(wordsArea.getText()), null, "",
            birthday);
    // Shut down bitcoinj and restart it with the new seed.
    Main.bitcoin.addListener(new Service.Listener() {
        @Override
        public void terminated(Service.State from) {
            Main.instance.setupWalletKit(seed);
            Main.bitcoin.startAsync();
        }
    }, Platform::runLater);
    Main.bitcoin.stopAsync();
}

From source file:co.cask.cdap.StandaloneMain.java

/**
 * Start the service./*from ww w  .  j a  v  a  2  s.  c  o  m*/
 */
public void startUp() throws Exception {
    // Workaround for release of file descriptors opened by URLClassLoader - https://issues.cask.co/browse/CDAP-2841
    URLConnections.setDefaultUseCaches(false);

    cleanupTempDir();

    // Start all the services.
    txService.startAndWait();
    metricsCollectionService.startAndWait();
    datasetService.startAndWait();
    serviceStore.startAndWait();
    streamService.startAndWait();

    // It is recommended to initialize log appender after datasetService is started,
    // since log appender instantiates a dataset.
    logAppenderInitializer.initialize();

    Service.State state = appFabricServer.startAndWait();
    if (state != Service.State.RUNNING) {
        throw new Exception("Failed to start Application Fabric");
    }

    metricsQueryService.startAndWait();
    router.startAndWait();
    if (userInterfaceService != null) {
        userInterfaceService.startAndWait();
    }

    if (securityEnabled) {
        externalAuthenticationServer.startAndWait();
    }

    if (exploreExecutorService != null) {
        exploreExecutorService.startAndWait();
    }

    String protocol = sslEnabled ? "https" : "http";
    int dashboardPort = sslEnabled ? configuration.getInt(Constants.Dashboard.SSL_BIND_PORT)
            : configuration.getInt(Constants.Dashboard.BIND_PORT);
    System.out.println("Standalone CDAP started successfully.");
    System.out.printf("Connect to the CDAP UI at %s://%s:%d\n", protocol, "localhost", dashboardPort);
}

From source file:co.cask.cdap.internal.app.services.HttpServiceTwillRunnable.java

/**
 * Starts the {@link NettyHttpService} and announces this runnable as well.
 *//*  w  w w.  j  a v  a2  s  .co m*/
@Override
public void run() {
    LOG.info("In run method in HTTP Service");
    Future<Service.State> completion = Services.getCompletionFuture(service);
    service.startAndWait();
    // announce the twill runnable
    int port = service.getBindAddress().getPort();
    Cancellable contextCancellable = getContext().announce(serviceName, port);
    LOG.info("Announced HTTP Service");

    // Create a Timer thread to periodically collect handler that are no longer in used and call destroy on it
    Timer timer = new Timer("http-handler-gc", true);
    timer.scheduleAtFixedRate(createHandlerDestroyTask(), HANDLER_CLEANUP_PERIOD_MS, HANDLER_CLEANUP_PERIOD_MS);

    try {
        completion.get();
    } catch (InterruptedException e) {
        LOG.error("Caught exception in HTTP Service run", e);
    } catch (ExecutionException e) {
        LOG.error("Caught exception in HTTP Service run", e);
    } finally {
        // once the service has been stopped, don't announce it anymore.
        contextCancellable.cancel();
        timer.cancel();

        // Go through all non-cleanup'ed handler and call destroy() upon them
        // At this point, there should be no call to any handler method, hence it's safe to call from this thread
        for (HandlerContextPair handlerContextPair : handlerReferences.values()) {
            try {
                handlerContextPair.close();
            } catch (IOException e) {
                LOG.error("Exception raised when closing the HttpServiceHandler of class {} and it's context.",
                        handlerContextPair.getClass(), e);
            }
        }
    }
}

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

private State convertState(Service.State state) {
    switch (state) {
    case FAILED://ww w .  j  av a  2  s  . c o m
        return State.FAILED;
    case NEW:
        return State.NEW;
    case RUNNING:
        return State.RUNNING;
    case STARTING:
        return State.STARTING;
    case STOPPING:
        return State.STOPPING;
    case TERMINATED:
        return State.TERMINATED;
    }
    throw new IllegalStateException("unknown state: " + state);
}

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

private void addThread() {
    log.debug("Adding new workload thread");
    Scenario<Object, Object, Object> scenario = command.getScenarioFactory().get(context);

    List<ScenarioCollector<?, ?, ?>> collectors = Lists.newLinkedList();
    for (KernelSideObjectProvider<ScenarioCollector<Object, Object, Object>> provider : command
            .getCollectors()) {//www .j a v  a  2 s.co m
        collectors.add(provider.provide(sessionId, command.getTaskId(), context));
    }

    WorkloadService.WorkloadServiceBuilder builder = WorkloadService.builder(scenario).addCollectors(collectors)
            .useExecutor(executor);
    WorkloadService thread = (predefinedSamplesCount())
            ? builder.buildServiceWithSharedSamplesCount(leftSamplesCount)
            : builder.buildInfiniteService();
    thread.changeDelay(delay);
    log.debug("Starting workload");
    Future<Service.State> future = thread.start();
    Service.State state = Futures.get(future, timeoutsConfiguration.getWorkloadStartTimeout());
    log.debug("Workload thread with is started with state {}", state);
    threads.add(thread);
}

From source file:co.cask.tigon.DistributedMain.java

public void startUp(PrintStream out) throws Exception {
    registerShutDownHook();/*from   w  ww  . j av a2 s  . c o m*/
    flowOperations.startAndWait();
    List<String> commandList = Lists.newArrayList();
    for (CLICommands cliCommand : CLICommands.values()) {
        commandList.add(cliCommand.toString().toLowerCase());
    }
    consoleReader.setPrompt("tigon> ");
    String line;
    while ((line = consoleReader.readLine()) != null) {
        String[] args = line.split("\\s+");
        String command = args[0].toUpperCase();
        try {
            CLICommands cmd = null;
            try {
                cmd = CLICommands.valueOf(command);
            } catch (IllegalArgumentException e) {
                out.println("Available Commands : ");
                out.println(StringUtils.join(commandList, ", "));
                continue;
            }

            if (args.length < cmd.getArgCount()) {
                throw new InvalidCLIArgumentException(cmd.printHelp());
            }

            if (cmd.equals(CLICommands.START)) {
                Map<String, String> runtimeArgs = Maps.newHashMap();
                if (args.length > cmd.getArgCount()) {
                    try {
                        runtimeArgs = DeployClient
                                .fromPosixArray(Arrays.copyOfRange(args, cmd.getArgCount(), args.length));
                    } catch (IllegalArgumentException e) {
                        LOG.error("Runtime Args are not in the correct format [ --key1=val1 --key2=val2 ]");
                        continue;
                    }
                }
                flowOperations.startFlow(new File(args[1]), args[2], runtimeArgs);
            } else if (cmd.equals(CLICommands.LIST)) {
                out.println(StringUtils.join(flowOperations.listAllFlows(), ", "));
            } else if (cmd.equals(CLICommands.STOP)) {
                flowOperations.stopFlow(args[1]);
            } else if (cmd.equals(CLICommands.DELETE)) {
                flowOperations.deleteFlow(args[1]);
            } else if (cmd.equals(CLICommands.SET)) {
                flowOperations.setInstances(args[1], args[2], Integer.valueOf(args[3]));
            } else if (cmd.equals(CLICommands.STATUS)) {
                Service.State state = flowOperations.getStatus(args[1]);
                String status = (state != null) ? state.toString() : "NOT FOUND";
                out.println(status);
            } else if (cmd.equals(CLICommands.FLOWLETINFO)) {
                out.println(String.format("%-20s %s", "Flowlet Name", "Instance Count"));
                Map<String, Integer> flowletInfoMap = flowOperations.getFlowInfo(args[1]);
                for (Map.Entry<String, Integer> flowletInfo : flowletInfoMap.entrySet()) {
                    out.println(String.format("%-20s %s", flowletInfo.getKey(), flowletInfo.getValue()));
                }
            } else if (cmd.equals(CLICommands.DISCOVER)) {
                for (InetSocketAddress socketAddress : flowOperations.discover(args[1], args[2])) {
                    out.println(String.format("%s:%s", socketAddress.getHostName(), socketAddress.getPort()));
                }
            } else if (cmd.equals(CLICommands.SHOWLOGS)) {
                flowOperations.addLogHandler(args[1], System.out);
            } else if (cmd.equals(CLICommands.SERVICEINFO)) {
                out.println(StringUtils.join(flowOperations.getServices(args[1]), "\n"));
            } else if (cmd.equals(CLICommands.VERSION)) {
                out.println(ProjectInfo.getVersion().getBuildVersion());
            } else if (cmd.equals(CLICommands.HELP)) {
                try {
                    out.println(CLICommands.valueOf(args[1].toUpperCase()).printHelp());
                } catch (IllegalArgumentException e) {
                    out.println("Command Not Found");
                }
            } else {
                //QUIT Command
                break;
            }
        } catch (InvalidCLIArgumentException e) {
            out.println(e.getMessage());
        }
    }
}