Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

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

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

private ListenableFuture<String> setRegistrationId(final Registration registration,
        final String registrationId) {
    registration.setRegistrationId(registrationId);

    final SettableFuture<String> resultFuture = SettableFuture.create();

    ListenableFuture<Void> upsertRegistrationInternalFuture = upsertRegistrationInternal(registration);

    Futures.addCallback(upsertRegistrationInternalFuture, new FutureCallback<Void>() {
        @Override//from  w w w . j a va2s  .  c  o  m
        public void onFailure(Throwable exception) {

            if (!(exception instanceof MobileServiceException)) {
                resultFuture.setException(exception);
            }

            MobileServiceException mobileServiceException = (MobileServiceException) exception;

            ServiceFilterResponse response = mobileServiceException.getResponse();

            if (response != null && response.getStatus().getStatusCode() == 410) {

                // if we get an RegistrationGoneException (410) from
                // service, we will recreate registration id and will try to
                // do upsert one more time.
                // This can occur if the backing NotificationHub is changed
                // or if the registration expires.

                try {
                    removeRegistrationId(registration.getName());
                } catch (Exception e) {
                    resultFuture.setException(e);
                    return;
                }

                ListenableFuture<String> createRegistrationIdFuture = createRegistrationId();

                Futures.addCallback(createRegistrationIdFuture, new FutureCallback<String>() {
                    @Override
                    public void onFailure(Throwable exception) {
                        resultFuture.setException(exception);
                    }

                    @Override
                    public void onSuccess(final String registrationId) {
                        ListenableFuture<Void> upsertRegistrationInternalFuture2 = upsertRegistrationInternal(
                                registration);

                        Futures.addCallback(upsertRegistrationInternalFuture2, new FutureCallback<Void>() {
                            @Override
                            public void onFailure(Throwable exception) {

                                if (!(exception instanceof MobileServiceException)) {
                                    resultFuture.setException(exception);
                                }

                                MobileServiceException mobileServiceException = (MobileServiceException) exception;

                                ServiceFilterResponse response = mobileServiceException.getResponse();

                                if (response != null && response.getStatus().getStatusCode() == 410) {

                                    RegistrationGoneException registrationGoneException = new RegistrationGoneException(
                                            mobileServiceException);
                                    resultFuture.setException(registrationGoneException);
                                }

                            }

                            public void onSuccess(Void v) {
                                try {
                                    storeRegistrationId(registration.getName(),
                                            registration.getRegistrationId(), registration.getPNSHandle());
                                } catch (Exception exception) {
                                    resultFuture.setException(exception);
                                    return;
                                }
                                resultFuture.set(registrationId);
                            }
                        });
                    }
                });
            } else {
                resultFuture.setException(exception);
            }
        }

        @Override
        public void onSuccess(Void v) {
            try {
                storeRegistrationId(registration.getName(), registration.getRegistrationId(),
                        registration.getPNSHandle());
            } catch (Exception exception) {
                resultFuture.setException(exception);
                return;
            }

            resultFuture.set(registrationId);
        }
    });

    return resultFuture;
}

From source file:es.udc.pfc.gameroom.AbstractRoom.java

@Override
public ListenableFuture<Void> configureRoom() {
    final SettableFuture<Void> future = SettableFuture.create();
    final Map<String, List<String>> fields = Maps.newHashMap();
    final List<String> no = ImmutableList.of("0");
    final List<String> si = ImmutableList.of("1");

    fields.put("muc#roomconfig_persistentroom", no);
    fields.put("muc#roomconfig_publicroom", no);
    fields.put("muc#roomconfig_membersonly", si);
    fields.put("muc#roomconfig_changesubject", no);

    final IQ config = new IQ(IQ.Type.set);
    config.setFrom(component.getJID());/*from   w ww  .j  av  a  2s  .c  o  m*/
    config.setTo(roomJID);
    final XMLElement data = config.addExtension("x", XMPPNamespaces.DATA);
    data.setAttribute("type", "submit");

    for (final Map.Entry<String, List<String>> field : fields.entrySet()) {
        final XMLElement f = data.addChild("field");
        f.setAttribute("var", field.getKey());
        for (final String value : field.getValue()) {
            f.addChild("value").setText(value);
        }
    }

    Futures.addCallback(component.sendIQ(config), new FutureCallback<IQ>() {
        @Override
        public void onSuccess(IQ result) {
            updateSubject();
            future.set(null);
        }

        @Override
        public void onFailure(Throwable t) {
            future.setException(t);
        }
    });

    return future;
}

From source file:com.microsoft.office365.starter.helpers.Authentication.java

public static SettableFuture<Void> authenticate(final Activity rootActivity,
        final DefaultDependencyResolver resolver, String resourceId) {

    final SettableFuture<Void> result = SettableFuture.create();

    getAuthenticationContext(rootActivity).acquireToken(rootActivity, resourceId, Constants.CLIENT_ID.trim(),
            Constants.REDIRECT_URI.trim(), PromptBehavior.Auto,
            new AuthenticationCallback<AuthenticationResult>() {

                @Override//  w ww.  ja v a  2s .c  o m
                public void onSuccess(final AuthenticationResult authenticationResult) {
                    if (authenticationResult != null
                            && !TextUtils.isEmpty(authenticationResult.getAccessToken())) {
                        resolver.setCredentialsFactory(new CredentialsFactory() {
                            @Override
                            public Credentials getCredentials() {
                                return new Credentials() {
                                    @Override
                                    public void prepareRequest(Request request) {
                                        request.addHeader("Authorization",
                                                "Bearer " + authenticationResult.getAccessToken());
                                    }
                                };
                            }
                        });
                        storeUserId(rootActivity, authenticationResult);
                        result.set(null);
                    }
                }

                private void storeUserId(final Activity rootActivity,
                        final AuthenticationResult authenticationResult) {

                    UserInfo ui = authenticationResult.getUserInfo();
                    SharedPreferences sharedPref = rootActivity.getPreferences(Context.MODE_PRIVATE);

                    if (ui != null) {
                        mLoggedInUser = ui.getUserId();
                        Editor editor = sharedPref.edit();
                        editor.putString("UserId", mLoggedInUser);
                        editor.putString("DisplayName", ui.getGivenName() + " " + ui.getFamilyName());
                        editor.commit();
                    } else {
                        mLoggedInUser = sharedPref.getString("UserId", "");
                    }
                }

                @Override
                public void onError(Exception exc) {
                    result.setException(exc);
                }
            });
    return result;
}

From source file:com.microsoft.sharepointservices.DocLibClient.java

/**
 * Gets children folder with a given path
 * /*from  ww  w .  j  a  v a  2 s  . c  o m*/
 * @param path
 * @return OfficeFuture<FileSystemItem>
 */
public ListenableFuture<List<FileSystemItem>> getFileSystemItems(String path, String library) {

    final SettableFuture<List<FileSystemItem>> result = SettableFuture.create();

    String getPath;

    if (library == null) {
        if (path == null || path.length() == 0) {
            getPath = getSiteUrl() + "_api/Files";
        } else {
            getPath = getSiteUrl() + String.format("_api/Files('%s')/children", urlEncode(path));
        }
    } else {
        if (path == null || path.length() == 0) {
            getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files", urlEncode(library));
        } else {
            getPath = getSiteUrl() + String.format("_api/web/lists/GetByTitle('%s')/files('%s')/children",
                    urlEncode(library), urlEncode(path));
        }
    }

    ListenableFuture<JSONObject> request = executeRequestJson(getPath, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            List<FileSystemItem> item;
            try {
                item = FileSystemItem.listFrom(json);
                result.set(item);
            } catch (Throwable e) {
                result.setException(e);
            }
        }
    });
    return result;
}

From source file:com.microsoft.office365.profile.util.AuthenticationManager.java

/**
 * Calls AuthenticationContext.acquireToken once to get tokens. User must provide credentials
 * the first time. Subsequent calls retrieve tokens from the local cache or use the refresh
 * token to get a valid access token./*w w  w  .  j a va 2s  .  c o  m*/
 * If all tokens expire, then the next call to getTokens will prompt for user credentials.
 * By default, you would use this in an asynchronous mode, but you can also call getTokens in
 * synchronously by appending get() to getTokens. For example, getTokens(null).get() which
 * will return an AuthenticationResult object.
 * @param authenticationCallback The callback to which delegate the execution flow.
 * @return A signal to wait on before continuing execution that contains an AuthenticationResult
 * object with information about the user, and the tokens.
 */
public synchronized SettableFuture<AuthenticationResult> getTokens(
        final AuthenticationCallback authenticationCallback) {

    final SettableFuture<AuthenticationResult> result = SettableFuture.create();

    if (verifyAuthenticationContext()) {
        getAuthenticationContext().acquireToken(this.mContextActivity, this.mResourceId, Constants.CLIENT_ID,
                Constants.REDIRECT_URI, PromptBehavior.Auto,
                new AuthenticationCallback<AuthenticationResult>() {
                    @Override
                    public void onSuccess(final AuthenticationResult authenticationResult) {
                        if (authenticationResult != null) {
                            if (authenticationCallback != null) {
                                if (authenticationResult.getStatus() == AuthenticationStatus.Succeeded) {
                                    authenticationCallback.onSuccess(authenticationResult);
                                } else {
                                    // Unknown error. Errors, like when the user cancels the
                                    // operation usually go through the onError method
                                    authenticationCallback.onError(new AuthenticationException(
                                            ADALError.AUTH_FAILED, "Authentication failed"));
                                }
                            }
                            result.set(authenticationResult);
                        } else {
                            result.setException(new AuthenticationException(ADALError.AUTH_FAILED,
                                    "Authentication failed"));
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (authenticationCallback != null) {
                            authenticationCallback.onError(e);
                        }
                        result.setException(e);
                    }
                });
    } else {
        result.setException(new Throwable(
                "Auth context verification failed. " + "Use setContextActivity(Activity) before getTokens()"));
    }
    return result;
}

From source file:com.google.devtools.build.lib.remote.AbstractRemoteActionCache.java

/**
 * Download the output files and directory trees of a remotely executed action to the local
 * machine, as well stdin / stdout to the given files.
 *
 * <p>In case of failure, this method deletes any output files it might have already created.
 *
 * @throws IOException in case of a cache miss or if the remote cache is unavailable.
 * @throws ExecException in case clean up after a failed download failed.
 *//*from  ww w . j  ava  2s.  co  m*/
// TODO(olaola): will need to amend to include the TreeNodeRepository for updating.
public void download(ActionResult result, Path execRoot, FileOutErr outErr)
        throws ExecException, IOException, InterruptedException {
    try {
        Context ctx = Context.current();
        List<FuturePathBooleanTuple> fileDownloads = Collections.synchronizedList(
                new ArrayList<>(result.getOutputFilesCount() + result.getOutputDirectoriesCount()));
        for (OutputFile file : result.getOutputFilesList()) {
            Path path = execRoot.getRelative(file.getPath());
            ListenableFuture<Void> download = retrier.executeAsync(
                    () -> ctx.call(() -> downloadFile(path, file.getDigest(), file.getContent())));
            fileDownloads.add(new FuturePathBooleanTuple(download, path, file.getIsExecutable()));
        }

        List<ListenableFuture<Void>> dirDownloads = new ArrayList<>(result.getOutputDirectoriesCount());
        for (OutputDirectory dir : result.getOutputDirectoriesList()) {
            SettableFuture<Void> dirDownload = SettableFuture.create();
            ListenableFuture<byte[]> protoDownload = retrier
                    .executeAsync(() -> ctx.call(() -> downloadBlob(dir.getTreeDigest())));
            Futures.addCallback(protoDownload, new FutureCallback<byte[]>() {
                @Override
                public void onSuccess(byte[] b) {
                    try {
                        Tree tree = Tree.parseFrom(b);
                        Map<Digest, Directory> childrenMap = new HashMap<>();
                        for (Directory child : tree.getChildrenList()) {
                            childrenMap.put(digestUtil.compute(child), child);
                        }
                        Path path = execRoot.getRelative(dir.getPath());
                        fileDownloads.addAll(downloadDirectory(path, tree.getRoot(), childrenMap, ctx));
                        dirDownload.set(null);
                    } catch (IOException e) {
                        dirDownload.setException(e);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    dirDownload.setException(t);
                }
            }, MoreExecutors.directExecutor());
            dirDownloads.add(dirDownload);
        }

        fileDownloads.addAll(downloadOutErr(result, outErr, ctx));

        for (ListenableFuture<Void> dirDownload : dirDownloads) {
            // Block on all directory download futures, so that we can be sure that we have discovered
            // all file downloads and can subsequently safely iterate over the list of file downloads.
            getFromFuture(dirDownload);
        }

        for (FuturePathBooleanTuple download : fileDownloads) {
            getFromFuture(download.getFuture());
            if (download.getPath() != null) {
                download.getPath().setExecutable(download.isExecutable());
            }
        }
    } catch (IOException downloadException) {
        try {
            // Delete any (partially) downloaded output files, since any subsequent local execution
            // of this action may expect none of the output files to exist.
            for (OutputFile file : result.getOutputFilesList()) {
                execRoot.getRelative(file.getPath()).delete();
            }
            for (OutputDirectory directory : result.getOutputDirectoriesList()) {
                FileSystemUtils.deleteTree(execRoot.getRelative(directory.getPath()));
            }
            if (outErr != null) {
                outErr.getOutputPath().delete();
                outErr.getErrorPath().delete();
            }
        } catch (IOException e) {
            // If deleting of output files failed, we abort the build with a decent error message as
            // any subsequent local execution failure would likely be incomprehensible.

            // We don't propagate the downloadException, as this is a recoverable error and the cause
            // of the build failure is really that we couldn't delete output files.
            throw new EnvironmentalExecException("Failed to delete output files after incomplete "
                    + "download. Cannot continue with local execution.", e, true);
        }
        throw downloadException;
    }
}

From source file:com.google.casinocoin.core.Peer.java

/**
 * <p>Returns a future that wraps a list of all transactions that the given transaction depends on, recursively.
 * Only transactions in peers memory pools are included; the recursion stops at transactions that are in the
 * current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and
 * a precondition checks this.</p>
 *
 * <p>For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and
 * has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D
 * that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.</p>
 *
 * <p>This method is useful for apps that want to learn about how long an unconfirmed transaction might take
 * to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying
 * transactions that depend on unconfirmed free transactions.</p>
 *
 * <p>Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.</p>
 *///from  w w  w  .j a v a2  s.c  o  m
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
    TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
    Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
    log.info("{}: Downloading dependencies of {}", vAddress, tx.getHashAsString());
    final LinkedList<Transaction> results = new LinkedList<Transaction>();
    // future will be invoked when the entire dependency tree has been walked and the results compiled.
    final ListenableFuture future = downloadDependenciesInternal(tx, new Object(), results);
    final SettableFuture<List<Transaction>> resultFuture = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback() {
        public void onSuccess(Object _) {
            resultFuture.set(results);
        }

        public void onFailure(Throwable throwable) {
            resultFuture.setException(throwable);
        }
    });
    return resultFuture;
}

From source file:org.apache.twill.discovery.ZKDiscoveryService.java

/**
 * Handle registration failure.//from ww  w  . j a v a  2  s.com
 *
 * @param discoverable The discoverable to register.
 * @param completion A settable future to set when registration is completed / failed.
 * @param creationCallback A future callback for path creation.
 * @param failureCause The original cause of failure.
 */
private void handleRegisterFailure(final Discoverable discoverable, final SettableFuture<String> completion,
        final FutureCallback<String> creationCallback, final Throwable failureCause) {
    if (closed.get()) {
        return;
    }

    final String path = getNodePath(discoverable);
    Futures.addCallback(zkClient.exists(path), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(@Nullable Stat result) {
            if (result == null) {
                // If the node is gone, simply retry.
                LOG.info("Node {} is gone. Retry registration for {}.", path, discoverable);
                retryRegister(discoverable, creationCallback);
                return;
            }

            long ephemeralOwner = result.getEphemeralOwner();
            if (ephemeralOwner == 0) {
                // it is not an ephemeral node, something wrong.
                LOG.error(
                        "Node {} already exists and is not an ephemeral node. Discoverable registration failed: {}.",
                        path, discoverable);
                completion.setException(failureCause);
                return;
            }
            Long sessionId = zkClient.getSessionId();
            if (sessionId == null || ephemeralOwner != sessionId) {
                // This zkClient is not valid or doesn't own the ephemeral node, simply keep retrying.
                LOG.info("Owner of {} is different. Retry registration for {}.", path, discoverable);
                retryRegister(discoverable, creationCallback);
            } else {
                // This client owned the node, treat the registration as completed.
                // This could happen if same client tries to register twice (due to mistake or failure race condition).
                completion.set(path);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            // If exists call failed, simply retry creation.
            LOG.warn("Error when getting stats on {}. Retry registration for {}.", path, discoverable);
            retryRegister(discoverable, creationCallback);
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

/**
 * Deletes a registration and removes it from local storage
 *
 * @param registrationName The registration Name
 * @param registrationId   The registration Id
 * @param callback         The operation callback
 * @throws java.util.concurrent.ExecutionException
 * @throws InterruptedException/*from  w w w .j  a  v  a  2 s.  c om*/
 */
private ListenableFuture<Void> deleteRegistrationInternal(final String registrationName,
        final String registrationId) {

    final SettableFuture<Void> resultFuture = SettableFuture.create();

    if (isNullOrWhiteSpace(registrationId)) {
        resultFuture.set(null);
        return resultFuture;
    }

    String path = PNS_API_URL + "/registrations/" + registrationId;

    ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, null, "DELETE",
            null, null);

    Futures.addCallback(serviceFilterFuture, new FutureCallback<ServiceFilterResponse>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(ServiceFilterResponse response) {
            removeRegistrationId(registrationName);

            resultFuture.set(null);
        }
    });

    return resultFuture;
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

@Override
public <T extends DataObject> CheckedFuture<Void, DTxException> mergeAndRollbackOnFailure(
        DTXLogicalTXProviderType logicalTXProviderType, LogicalDatastoreType logicalDatastoreType,
        InstanceIdentifier<T> instanceIdentifier, T t, InstanceIdentifier<?> nodeId) {
    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    final DTXReadWriteTransaction transaction = this.perNodeTransactionsbyLogicalType.get(logicalTXProviderType)
            .get(nodeId);/*from  w  w w  .j  a v  a2 s.co  m*/

    CheckedFuture<Void, DTxException> mergeFuture = transaction.asyncMerge(logicalDatastoreType,
            instanceIdentifier, t);

    final SettableFuture<Void> retFuture = SettableFuture.create();

    Futures.addCallback(mergeFuture, new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void aVoid) {
            retFuture.set(null);
        }

        @Override
        public void onFailure(Throwable throwable) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback();
                    Futures.addCallback(rollExcept, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void aVoid) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.EditFailedException(
                                    "Failed to merge but succeed to rollback"));
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.RollbackFailedException(throwable));
                        }
                    });
                }
            };

            new Thread(runnable).start();
        }
    });

    return Futures.makeChecked(retFuture, new Function<Exception, DTxException>() {
        @Nullable
        @Override
        public DTxException apply(@Nullable Exception e) {
            e = (Exception) e.getCause();
            return e instanceof DTxException ? (DTxException) e
                    : new DTxException("Merge failed and rollback failure", e);
        }
    });
}