Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:com.google.gapid.util.UpdateWatcher.java

private void doCheck() {
    if (settings.autoCheckForUpdates) {
        ListenableFuture<Release> future = client.checkForUpdates(INCLUDE_PRE_RELEASES);
        settings.updateAvailable = false;
        try {/*from w  w w  .j a v a2s. c  o  m*/
            Release release = future.get();
            if (release != null) {
                settings.updateAvailable = true;
                listener.onNewReleaseAvailable(release);
            }
        } catch (InterruptedException | ExecutionException e) {
            /* never mind */
        }
    }
    settings.lastCheckForUpdates = System.currentTimeMillis();
    settings.save();
    scheduleCheck();
}

From source file:com.github.nethad.clustermeister.integration.sc06.Scenario06.java

@Override
public void runScenario() {
    logger.info("Scenario 06 started...");

    Clustermeister clustermeister = ClustermeisterFactory.create();
    try {/*  w  w  w  .  j  ava  2s. c  o  m*/
        logger.info("Clustermeister started.");
        logger.info("Getting nodes...");
        Collection<ExecutorNode> allNodes = clustermeister.getAllNodes();
        addToReport("node size", allNodes.size());
        logger.info(allNodes.size() + " nodes found.");

        ListenableFuture<?> proxyAddressFuture = allNodes.iterator().next()
                .execute(new ProxyBootstrap(AkkaConfig.get()));

        String proxyAddress = (String) proxyAddressFuture.get();

        ActorSystem system = ActorSystem.create("MainSystem", AkkaConfig.get());

        ActorRef proxyActor = system.actorFor(proxyAddress);

        Node proxiedNode = AkkaProxy.newStringProxy(proxyActor);

        Integer cores1 = proxiedNode.numberOfCores();

        //         Integer expected1 = Runtime.getRuntime().availableProcessors();

        //         System.out.println("First result: " + cores1);

        //         Assertions.assertEquals(expected1, cores1,
        //               "Result is not as expected.");
        addToReport("first result", cores1);

        akka.dispatch.Future<Object> coresFuture = ask(proxyActor, ExampleRequests.simpleNumberOfCores(),
                100000);
        Integer cores2 = (Integer) Await.result(coresFuture, new FiniteDuration(100, "Seconds"));

        System.out.println("Second result: " + cores2);
        addToReport("second result", cores2);

        //         Integer expected2 = Runtime.getRuntime().availableProcessors();

        //         Assertions.assertEquals(expected2, cores2,
        //               "Result is not as expected.");

    } catch (Exception ex) {
        logger.warn("Exception on result", ex);
        addToReport("Exception on result", ex);
    } finally {
        clustermeister.shutdown();
    }
}

From source file:c5db.webadmin.StatusHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (!target.equals("/")) {
        return;//  w  w  w .ja  v  a 2  s.c  o m
    }
    try {

        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        Mustache template = service.getMustacheFactory().compile("templates/index.mustache");
        // TODO consider BufferedWriter( ) for performance
        Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");

        // Collect server status objects from around this place.
        ImmutableMap<ModuleType, C5Module> modules = service.getServer().getModules();
        DiscoveryModule discoveryModule = (DiscoveryModule) service.getServer().getModule(ModuleType.Discovery)
                .get();
        ListenableFuture<ImmutableMap<Long, NodeInfo>> nodeFuture = discoveryModule.getState();
        ImmutableMap<Long, NodeInfo> nodes = nodeFuture.get();

        TabletModule tabletModule = (TabletModule) service.getServer().getModule(ModuleType.Tablet).get();
        Collection<Tablet> tablets = tabletModule.getTablets();

        TopLevelHolder templateContext = new TopLevelHolder(service.getServer(), modules, nodes, tablets);
        template.execute(writer, templateContext);
        writer.flush();

    } catch (ExecutionException | InterruptedException | TimeoutException e) {
        throw new IOException("Getting status", e);
    }
}

From source file:org.opendaylight.atrium.cli.FibCommand.java

@Override
protected Object doExecute() throws Exception {

    DataBroker dataBroker = AtriumCli.getDataBroker();
    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
    InstanceIdentifier<FibEntries> instanceIdentifier = InstanceIdentifier.builder(FibEntries.class).build();

    FibEntries fibEntries = null;/*w w w  . j  av  a 2 s.  c o m*/
    try {
        ListenableFuture<Optional<FibEntries>> lfONT;
        lfONT = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, instanceIdentifier);
        Optional<FibEntries> oNT = lfONT.get();
        fibEntries = oNT.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } finally {
        readOnlyTransaction.close();
    }

    for (FibEntry fibEntry : fibEntries.getFibEntry()) {
        String prefix = fibEntry.getPrefix();
        Type type = fibEntry.getType();
        IpAddress ipAddress = fibEntry.getNextHopIp();
        MacAddress macAddress = fibEntry.getNextHopMac();

        System.out.println("Type : " + type + "\tNext Hop Ip : " + ipAddress.getIpv4Address().getValue()
                + "\tPrefix : " + prefix + "\tNext Hop Mac : " + macAddress);
    }

    return null;
}

From source file:co.cask.cdap.logging.framework.distributed.DistributedLogFramework.java

/**
 * Blocks and validates all the given futures completed successfully.
 *//*www .ja v  a 2 s .c  o m*/
private void validateAllFutures(Iterable<? extends ListenableFuture<?>> futures) throws Exception {
    // The get call shouldn't throw exception. It just block until all futures completed.
    Futures.successfulAsList(futures).get();

    // Iterates all futures to make sure all of them completed successfully
    Throwable exception = null;
    for (ListenableFuture<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException e) {
            if (exception == null) {
                exception = e.getCause();
            } else {
                exception.addSuppressed(e.getCause());
            }
        }
    }

    // Throw exception if any of the future failed.
    if (exception != null) {
        if (exception instanceof Exception) {
            throw (Exception) exception;
        }
        throw new RuntimeException(exception);
    }
}

From source file:com.github.nethad.clustermeister.integration.sc06.TorqueScenario.java

private void execute() {
    report = new ArrayList<String>();
    logger.info("Scenario 06 started...");

    Clustermeister clustermeister = ClustermeisterFactory.create();
    try {/*  w  w w .  j a  va 2 s. c  o  m*/
        logger.info("Clustermeister started.");
        logger.info("Getting nodes...");
        Collection<ExecutorNode> allNodes = clustermeister.getAllNodes();
        addToReport("node size", allNodes.size());
        logger.info(allNodes.size() + " nodes found.");

        ListenableFuture<?> proxyAddressFuture = allNodes.iterator().next()
                .execute(new ProxyBootstrap(AkkaConfig.get()));

        String proxyAddress = (String) proxyAddressFuture.get();

        ActorSystem system = ActorSystem.create("MainSystem", AkkaConfig.get());

        ActorRef proxyActor = system.actorFor(proxyAddress);

        Node proxiedNode = AkkaProxy.newStringProxy(proxyActor);

        Integer cores1 = proxiedNode.numberOfCores();

        //         Integer expected1 = Runtime.getRuntime().availableProcessors();

        //         System.out.println("First result: " + cores1);

        //         Assertions.assertEquals(expected1, cores1,
        //               "Result is not as expected.");
        addToReport("first result", cores1);

        akka.dispatch.Future<Object> coresFuture = ask(proxyActor, ExampleRequests.simpleNumberOfCores(),
                100000);
        Integer cores2 = (Integer) Await.result(coresFuture, new FiniteDuration(100, "Seconds"));

        System.out.println("Second result: " + cores2);
        addToReport("second result", cores2);

        //         Integer expected2 = Runtime.getRuntime().availableProcessors();

        //         Assertions.assertEquals(expected2, cores2,
        //               "Result is not as expected.");

    } catch (Exception ex) {
        logger.warn("Exception on result", ex);
        addToReport("Exception on result", ex);
    } finally {
        clustermeister.shutdown();
        System.out.println("EXECUTION REPORT:");
        for (String line : report) {
            System.out.println(line);
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.operations.RemoteTableOperationProcessor.java

@Override
public JsonObject visit(DeleteOperation operation) throws Throwable {
    MobileServiceJsonTable table = this.getRemoteTable(operation.getTableName());
    ListenableFuture<Void> future = table.delete(this.mItem);

    try {//w  w  w .  ja  v  a2  s . c om
        future.get();

        return null;
    } catch (ExecutionException ex) {

        if (!ExceptionIs404NotFound(ex)) {
            throw ex.getCause();
        }

        return null;
    }
}

From source file:org.opendaylight.ovsdb.hwvtepsouthbound.transact.TransactInvokerImpl.java

@Override
public void invoke(TransactCommand command) {
    TransactionBuilder tb = new TransactionBuilder(connectionInstance.getOvsdbClient(), dbSchema);
    command.execute(tb);/*from   w w  w.  j av a2  s. co m*/
    ListenableFuture<List<OperationResult>> result = tb.execute();
    LOG.debug("invoke: command: {}, tb: {}", command, tb);
    if (tb.getOperations().size() > 0) {
        try {
            List<OperationResult> got = result.get();
            LOG.debug("OVSDB transaction result: {}", got);
        } catch (Exception e) {
            LOG.warn("Transact execution exception: ", e);
        }
        LOG.trace("invoke exit command: {}, tb: {}", command, tb);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.operations.RemoteTableOperationProcessor.java

@Override
public JsonObject visit(InsertOperation operation) throws Throwable {
    MobileServiceJsonTable table = this.getRemoteTable(operation.getTableName());
    table.setSystemProperties(EnumSet.allOf(MobileServiceSystemProperty.class));

    JsonObject item = removeSystemProperties(this.mItem);

    ListenableFuture<JsonObject> future = table.insert(item);

    try {//from w w w.  j  a  v  a 2s .c  o m
        return future.get();
    } catch (ExecutionException ex) {
        throw ex.getCause();
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.operations.RemoteTableOperationProcessor.java

@Override
public JsonObject visit(UpdateOperation operation) throws Throwable {
    MobileServiceJsonTable table = this.getRemoteTable(operation.getTableName());
    table.setSystemProperties(getSystemProperties(this.mItem));

    ListenableFuture<JsonObject> future = table.update(this.mItem);

    try {/*  w  w w.  ja v a 2  s  .  c  om*/
        return future.get();
    } catch (ExecutionException ex) {
        throw ex.getCause();
    }
}