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:org.onosproject.store.device.impl.ECDeviceStore.java

@Override
public DeviceEvent removeDevice(DeviceId deviceId) {
    NodeId master = mastershipService.getMasterFor(deviceId);
    // if there exist a master, forward
    // if there is no master, try to become one and process
    boolean relinquishAtEnd = false;
    if (master == null) {
        final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
        if (myRole != MastershipRole.NONE) {
            relinquishAtEnd = true;//from   www  . j  a  v a2s .c  o  m
        }
        log.debug("Temporarily requesting role for {} to remove", deviceId);
        MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
        if (role == MastershipRole.MASTER) {
            master = localNodeId;
        }
    }

    if (!localNodeId.equals(master)) {
        log.debug("{} has control of {}, forwarding remove request", master, deviceId);

        clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master)
                .whenComplete((r, e) -> {
                    if (e != null) {
                        log.error("Failed to forward {} remove request to its master", deviceId, e);
                    }
                });
        return null;
    }

    // I have control..
    DeviceEvent event = null;
    final DeviceKey deviceKey = new DeviceKey(getPrimaryProviderId(deviceId), deviceId);
    DeviceDescription removedDeviceDescription = deviceDescriptions.remove(deviceKey);
    if (removedDeviceDescription != null) {
        event = purgeDeviceCache(deviceId);
    }

    if (relinquishAtEnd) {
        log.debug("Relinquishing temporary role acquired for {}", deviceId);
        mastershipService.relinquishMastership(deviceId);
    }
    return event;
}

From source file:org.jclouds.openstack.swift.v1.blobstore.RegionScopedSwiftBlobStore.java

@Override
@Beta/*from www.  j  a  v  a2s.c  o  m*/
public void downloadBlob(String container, String name, File destination, ExecutorService executor) {

    ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
    RandomAccessFile raf = null;
    File tempFile = new File(destination.getName() + "." + UUID.randomUUID());
    try {
        long contentLength = api.getObjectApi(regionId, container).getWithoutBody(name).getPayload()
                .getContentMetadata().getContentLength();

        // Reserve space for performance reasons
        raf = new RandomAccessFile(tempFile, "rw");
        raf.seek(contentLength - 1);
        raf.write(0);

        // Determine download buffer size, smaller means less memory usage; larger is faster as long as threads are saturated
        long partSize = getMinimumMultipartPartSize();

        // Loop through ranges within the file
        long from;
        long to;
        List<ListenableFuture<Void>> results = new ArrayList<ListenableFuture<Void>>();

        for (from = 0; from < contentLength; from = from + partSize) {
            to = (from + partSize >= contentLength) ? contentLength - 1 : from + partSize - 1;
            BlobDownloader b = new BlobDownloader(regionId, container, name, raf, from, to);
            results.add(listeningExecutor.submit(b));
        }

        Futures.getUnchecked(Futures.allAsList(results));

        raf.getChannel().force(true);
        raf.getChannel().close();
        raf.close();

        if (destination.exists()) {
            destination.delete();
        }
        if (!tempFile.renameTo(destination)) {
            throw new RuntimeException(
                    "Could not move temporary downloaded file to destination " + destination);
        }
        tempFile = null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        Closeables2.closeQuietly(raf);
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.android.contacts.activities.PeopleActivity.java

private void selectAccountForNewGroup() {
    // This should never block because the DrawerFragment loads the accounts and the
    // "Create Label" item only exists when that loading finishes
    final List<AccountInfo> accounts = Futures.getUnchecked(AccountTypeManager.getInstance(this)
            .filterAccountsAsync(AccountTypeManager.AccountFilter.GROUPS_WRITABLE));
    if (accounts.isEmpty()) {
        // We shouldn't present the add group button if there are no writable accounts
        // but check it since it's possible we are started with an Intent.
        Toast.makeText(this, R.string.groupCreateFailedToast, Toast.LENGTH_SHORT).show();
        return;/*from   w  w w.j a  v a 2 s  .  c  o  m*/
    }
    // If there is a single writable account, use it w/o showing a dialog.
    if (accounts.size() == 1) {
        onAccountChosen(accounts.get(0).getAccount(), /* extraArgs */ null);
        return;
    }
    SelectAccountDialogFragment.show(getFragmentManager(), R.string.dialog_new_group_account,
            AccountTypeManager.AccountFilter.GROUPS_WRITABLE, /* extraArgs */ null, TAG_SELECT_ACCOUNT_DIALOG);
}

From source file:com.facebook.buck.rules.CachingBuildRuleBuilder.java

private CacheResult fetch(ArtifactCache artifactCache, RuleKey ruleKey, LazyPath outputPath) {
    CacheResult cacheResult = Futures.getUnchecked(artifactCache.fetchAsync(ruleKey, outputPath));
    if (cacheResult.getType() != CacheResultType.HIT) {
        return cacheResult;
    }/*from  w ww  .  jav a2 s . c o  m*/
    for (String ruleKeyName : BuildInfo.RULE_KEY_NAMES) {
        if (!cacheResult.getMetadata().containsKey(ruleKeyName)) {
            continue;
        }
        String ruleKeyValue = cacheResult.getMetadata().get(ruleKeyName);
        try {
            verify(ruleKeyValue);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format(
                    "Invalid '%s' rule key in metadata for artifact '%s' returned by cache '%s': '%s'",
                    ruleKeyName, ruleKey, artifactCache.getClass(), ruleKeyValue), e);
        }
    }
    return cacheResult;
}

From source file:org.bitcoinj_extra.core.PeerGroup.java

@VisibleForTesting
void waitForJobQueue() {
    Futures.getUnchecked(executor.submit(Runnables.doNothing()));
}

From source file:org.bitcoinj_extra.core.PeerGroup.java

/** Does a blocking startup. */
public void start() {
    Futures.getUnchecked(startAsync());
}

From source file:org.apache.qpid.server.virtualhost.AbstractVirtualHost.java

private void postCreateDefaultExchangeTasks() {
    if (getContextValue(Boolean.class, USE_ASYNC_RECOVERY)) {
        _messageStoreRecoverer = new AsynchronousMessageStoreRecoverer();
    } else {/*from   www. j  a v  a2s .com*/
        _messageStoreRecoverer = new SynchronousMessageStoreRecoverer();
    }

    // propagate any exception thrown during recovery into HouseKeepingTaskExecutor to handle them accordingly
    // TODO if message recovery fails we ought to be transitioning the VH into ERROR and releasing the thread-pools etc.
    final ListenableFuture<Void> recoveryResult = _messageStoreRecoverer.recover(this);
    recoveryResult.addListener(new Runnable() {
        @Override
        public void run() {
            Futures.getUnchecked(recoveryResult);
        }
    }, _houseKeepingTaskExecutor);

    State finalState = State.ERRORED;
    try {
        initialiseHouseKeeping(getHousekeepingCheckPeriod());
        finalState = State.ACTIVE;
        _acceptsConnections.set(true);
    } finally {
        setState(finalState);
        reportIfError(getState());
    }
}