Example usage for com.google.common.util.concurrent Futures getUnchecked

List of usage examples for com.google.common.util.concurrent Futures getUnchecked

Introduction

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

Prototype

@GwtIncompatible("TODO")
public static <V> V getUnchecked(Future<V> future) 

Source Link

Document

Returns the result of calling Future#get() uninterruptibly on a task known not to throw a checked exception.

Usage

From source file:com.android.contacts.interactions.ImportDialogFragment.java

/**
 * Handle "import from SD"./*from  w  w  w.  java2 s  . c o m*/
 */
private void handleImportRequest(int resId, int subscriptionId) {
    // Get the accounts. Because this only happens after a user action this should pretty
    // much never block since it will usually be at least several seconds before the user
    // interacts with the view
    final List<AccountWithDataSet> accountList = AccountInfo
            .extractAccounts(Futures.getUnchecked(mAccountsFuture));

    // There are three possibilities:
    // - more than one accounts -> ask the user
    // - just one account -> use the account without asking the user
    // - no account -> use phone-local storage without asking the user
    final int size = accountList.size();
    if (size > 1) {
        // Send over to the account selector
        final Bundle args = new Bundle();
        args.putInt(KEY_RES_ID, resId);
        args.putInt(KEY_SUBSCRIPTION_ID, subscriptionId);
        SelectAccountDialogFragment.show(getFragmentManager(), R.string.dialog_new_contact_account,
                AccountTypeManager.AccountFilter.CONTACTS_WRITABLE, args);
    } else {
        AccountSelectionUtil.doImport(getActivity(), resId, (size == 1 ? accountList.get(0) : null),
                (CompatUtils.isMSIMCompatible() ? subscriptionId : -1));
    }
}

From source file:com.palantir.atlasdb.keyvalue.impl.TieredKeyValueService.java

@Override
public void truncateTables(final Set<String> tableNames) {
    final Set<String> truncateOnPrimary = Sets.newHashSet();
    final Set<String> truncateOnSecondary = Sets.newHashSet();

    for (String tableName : tableNames) {
        if (isNotTiered(tableName)) {
            truncateOnPrimary.add(tableName);
        } else {/*ww w.  ja va 2 s.co  m*/
            truncateOnPrimary.add(tableName);
            truncateOnSecondary.add(tableName);
        }

        Future<?> primaryFuture = executor.submit(new Runnable() {
            @Override
            public void run() {
                primary.truncateTables(truncateOnPrimary);
            }
        });
        secondary.truncateTables(truncateOnSecondary);
        Futures.getUnchecked(primaryFuture);
    }
}

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

/**
 * Adds a listener to the {@link ProgramController} and blocks for completion.
 *
 * @param closeable a {@link Closeable} to call when the program execution completed
 * @param controller the {@link ProgramController} for the program
 * @throws Exception if the execution failed
 *//*from   www  . j  a v a2s. c  om*/
private void blockForCompletion(final Closeable closeable, final ProgramController controller)
        throws Exception {
    // Execute the program.
    final SettableFuture<Void> completion = SettableFuture.create();
    controller.addListener(new AbstractListener() {

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            switch (currentState) {
            case COMPLETED:
                completed();
                break;
            case KILLED:
                killed();
                break;
            case ERROR:
                error(cause);
                break;
            }
        }

        @Override
        public void completed() {
            Closeables.closeQuietly(closeable);
            nodeStates.put(nodeId,
                    new WorkflowNodeState(nodeId, NodeStatus.COMPLETED, controller.getRunId().getId(), null));
            completion.set(null);
        }

        @Override
        public void killed() {
            Closeables.closeQuietly(closeable);
            nodeStates.put(nodeId,
                    new WorkflowNodeState(nodeId, NodeStatus.KILLED, controller.getRunId().getId(), null));
            completion.set(null);
        }

        @Override
        public void error(Throwable cause) {
            Closeables.closeQuietly(closeable);
            nodeStates.put(nodeId,
                    new WorkflowNodeState(nodeId, NodeStatus.FAILED, controller.getRunId().getId(), cause));
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Block for completion.
    try {
        completion.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw Throwables.propagate(cause);
    } catch (InterruptedException e) {
        try {
            Futures.getUnchecked(controller.stop());
        } catch (Throwable t) {
            // no-op
        }
        // reset the interrupt
        Thread.currentThread().interrupt();
    }
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.FlowCapableNodeConnectorListener.java

private Map<Name, EndpointL3> readL3EpsWithOfOverlayAugByPortName(ReadTransaction rTx) {
    Optional<Endpoints> potentialEps = Futures
            .getUnchecked(rTx.read(LogicalDatastoreType.OPERATIONAL, endpointsIid));
    if (!potentialEps.isPresent() || potentialEps.get().getEndpoint() == null) {
        return Collections.emptyMap();
    }/*ww  w .  j  a v a  2  s  .c  om*/
    Map<Name, EndpointL3> epsByPortName = new HashMap<>();
    for (EndpointL3 epL3 : potentialEps.get().getEndpointL3()) {
        OfOverlayL3Context ofOverlayL3Ep = epL3.getAugmentation(OfOverlayL3Context.class);
        if (ofOverlayL3Ep != null && ofOverlayL3Ep.getPortName() != null) {
            epsByPortName.put(ofOverlayL3Ep.getPortName(), epL3);
        }
    }
    return epsByPortName;
}

From source file:zipkin.cassandra.CassandraSpanStore.java

/** Used for testing */
void clear() {/*w w  w  .  ja v a  2s .com*/
    try (Session session = cluster.connect()) {
        List<ListenableFuture<?>> futures = new LinkedList<>();
        for (String cf : ImmutableList.of("traces", "dependencies", "service_names", "span_names",
                "service_name_index", "service_span_name_index", "annotations_index", "span_duration_index")) {
            futures.add(session.executeAsync(format("TRUNCATE %s.%s", keyspace, cf)));
        }
        Futures.getUnchecked(Futures.allAsList(futures));
    }
}

From source file:com.spotify.helios.testing.TemporaryJob.java

private void awaitUp(final String host) throws TimeoutException {
    final TemporaryJobReports.Step startContainer = reportWriter.step("start container")
            .tag("jobId", job.getId()).tag("host", host).tag("image", job.getImage());
    try {// w  w  w.j  a va  2  s .  co m
        final AtomicBoolean messagePrinted = new AtomicBoolean(false);
        final TaskStatus status = Polling.awaitUnchecked(deployTimeoutMillis, MILLISECONDS,
                job.getId() + " was not up within %d %s", new Callable<TaskStatus>() {
                    @Override
                    public TaskStatus call() throws Exception {
                        final JobStatus status = Futures.getUnchecked(client.jobStatus(job.getId()));
                        if (status == null) {
                            log.debug("Job status not available");
                            return null;
                        }
                        final TaskStatus taskStatus = status.getTaskStatuses().get(host);
                        if (taskStatus == null) {
                            log.debug("Task status not available on {}", host);
                            return null;
                        }

                        if (!messagePrinted.get() && !isNullOrEmpty(jobDeployedMessageFormat)
                                && !isNullOrEmpty(taskStatus.getContainerId())) {
                            outputDeployedMessage(host, taskStatus.getContainerId());
                            messagePrinted.set(true);
                        }

                        verifyHealthy(host, taskStatus);

                        final TaskStatus.State state = taskStatus.getState();
                        log.info("Job state of {}: {}", job.getImage(), state);

                        if (state == TaskStatus.State.RUNNING) {
                            return taskStatus;
                        }

                        return null;
                    }
                });

        statuses.put(host, status);

        startContainer.markSuccess();
    } finally {
        startContainer.finish();
    }

    final TemporaryJobReports.Step probe = reportWriter.step("probe").tag("jobId", job.getId()).tag("host",
            host);
    try {
        for (final String port : waitPorts) {
            awaitPort(port, host);
        }

        probe.markSuccess();
    } finally {
        probe.finish();
    }
}

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

@Override
public void run() {
    LOG.info("Starting metrics service");
    Futures.getUnchecked(Services.chainStart(zkClientService, kafkaClientService, metricsCollectionService,
            streamCoordinatorClient, resourceReporter));

    LOG.info("Starting runnable: {}", name);
    controller = injector.getInstance(getProgramClass()).run(program, programOpts);
    final SettableFuture<ProgramController.State> state = SettableFuture.create();
    controller.addListener(new AbstractListener() {

        @Override/*from  w w w .  jav  a2  s.  c  o m*/
        public void alive() {
            runlatch.countDown();
        }

        @Override
        public void init(ProgramController.State currentState, @Nullable Throwable cause) {
            if (currentState == ProgramController.State.ALIVE) {
                alive();
            } else {
                super.init(currentState, cause);
            }
        }

        @Override
        public void completed() {
            state.set(ProgramController.State.COMPLETED);
        }

        @Override
        public void killed() {
            state.set(ProgramController.State.KILLED);
        }

        @Override
        public void error(Throwable cause) {
            LOG.error("Program runner error out.", cause);
            state.setException(cause);
        }
    }, MoreExecutors.sameThreadExecutor());

    try {
        state.get();
        LOG.info("Program stopped.");
    } catch (InterruptedException e) {
        LOG.warn("Program interrupted.", e);
    } catch (ExecutionException e) {
        LOG.error("Program execution failed.", e);
        if (propagateServiceError()) {
            throw Throwables.propagate(Throwables.getRootCause(e));
        }
    } finally {
        // Always unblock the handleCommand method if it is not unblocked before (e.g if program failed to start).
        // The controller state will make sure the corresponding command will be handled correctly in the correct state.
        runlatch.countDown();
    }
}

From source file:org.bitcoinj_extra.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(Coin amount) {
    // Not enough money in the wallet.
    Coin amountPlusFee = amount.add(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<Coin> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out//  www.  j  ava2s. c o m
                .println("Please send " + amountPlusFee.toFriendlyString() + " to " + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }
}

From source file:com.palantir.atlasdb.keyvalue.impl.TieredKeyValueService.java

@Override
public void delete(final String tableName, final Multimap<Cell, Long> keys) {
    if (isNotTiered(tableName)) {
        primary.delete(tableName, keys);
        return;/*from w  w w  .  j av  a 2 s  .  c  o  m*/
    }
    Future<?> primaryFuture = executor.submit(new Runnable() {
        @Override
        public void run() {
            primary.delete(tableName, keys);
        }
    });
    secondary.delete(tableName, keys);
    Futures.getUnchecked(primaryFuture);
}

From source file:com.palantir.atlasdb.keyvalue.impl.AbstractKeyValueService.java

@Override
public void truncateTables(final Set<String> tableNames) {
    List<Future<Void>> futures = Lists.newArrayList();
    for (final String tableName : tableNames) {
        futures.add(executor.submit(new Callable<Void>() {
            @Override//from w w w.  jav  a2 s . com
            public Void call() throws Exception {
                truncateTable(tableName);
                return null;
            }
        }));
    }

    for (Future<Void> future : futures) {
        Futures.getUnchecked(future);
    }
}