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.android.builder.internal.aapt.v1.AaptV1.java

@NonNull
@Override//from w w w  . j a va 2s .  co m
public ListenableFuture<File> compile(@NonNull File file, @NonNull File output) throws AaptException {
    ListenableFuture<File> compilationFuture;

    /*
     * Do not compile raw resources.
     */
    if (ResourceFolderType.getFolderType(file.getParentFile().getName()) == ResourceFolderType.RAW) {
        return Futures.immediateFuture(null);
    }

    if (mCruncher == null) {
        /*
         * Revert to old-style crunching.
         */
        compilationFuture = super.compile(file, output);
    } else {
        Preconditions.checkArgument(file.isFile(), "!file.isFile()");
        Preconditions.checkArgument(output.isDirectory(), "!output.isDirectory()");

        SettableFuture<File> future = SettableFuture.create();
        compilationFuture = future;

        if (!mProcessMode.shouldProcess(file)) {
            future.set(null);
        } else {
            File outputFile = compileOutputFor(file, output);

            try {
                Files.createParentDirs(outputFile);
            } catch (IOException e) {
                throw new AaptException(e, String.format("Failed to create parent directories for file '%s'",
                        output.getAbsolutePath()));
            }

            int key = mCruncher.start();
            try {
                mCruncher.crunchPng(key, file, outputFile);
            } catch (PngException e) {
                throw new AaptException(e, String.format("Failed to crunch file '%s' into '%s'",
                        file.getAbsolutePath(), outputFile.getAbsolutePath()));
            }

            mWaitExecutor.execute(() -> {
                try {
                    mCruncher.end(key);
                    future.set(outputFile);
                } catch (Exception e) {
                    future.setException(e);
                }
            });
        }
    }

    /*
     * When the compilationFuture is complete, check if the generated file is not bigger than
     * the original file. If the original file is smaller, copy the original file over the
     * generated file.
     *
     * However, this doesn't work with 9-patch because those need to be processed.
     *
     * Return a new future after this verification is done.
     */
    if (file.getName().endsWith(SdkConstants.DOT_9PNG)) {
        return compilationFuture;
    }

    return Futures.transform(compilationFuture, (File result) -> {
        SettableFuture<File> returnFuture = SettableFuture.create();

        try {
            if (result != null && file.length() < result.length()) {
                Files.copy(file, result);
            }

            returnFuture.set(result);
        } catch (Exception e) {
            returnFuture.setException(e);
        }

        return returnFuture;
    });
}

From source file:org.apache.twill.internal.container.TwillContainerService.java

@Override
public ListenableFuture<String> onReceived(final String messageId, final Message message) {
    LOG.debug("Message received: {} {}.", messageId, message);

    if (handleSecureStoreUpdate(message)) {
        return Futures.immediateFuture(messageId);
    }// w  w w  .  j  av a 2s.c  om

    final SettableFuture<String> result = SettableFuture.create();
    Command command = message.getCommand();
    if (message.getType() == Message.Type.SYSTEM && "instances".equals(command.getCommand())
            && command.getOptions().containsKey("count")) {
        context.setInstanceCount(Integer.parseInt(command.getOptions().get("count")));
    }

    String commandStr = command.getCommand();
    if (message.getType() == Message.Type.SYSTEM) {
        boolean handled = false;
        if (SystemMessages.SET_LOG_LEVEL.equals(commandStr)) {
            // The options is a map from logger name to log level.
            setLogLevels(command.getOptions());
            handled = true;
        } else if (SystemMessages.RESET_LOG_LEVEL.equals(commandStr)) {
            // The options is a set of loggers to reset in the form of loggerName -> loggerName map.
            resetLogLevels(command.getOptions().keySet());
            handled = true;
        }

        if (handled) {
            updateLiveNode();
            return Futures.immediateFuture(messageId);
        }
    }

    commandExecutor.execute(new Runnable() {

        @Override
        public void run() {
            try {
                runnable.handleCommand(message.getCommand());
                result.set(messageId);
            } catch (Exception e) {
                result.setException(e);
            }
        }
    });
    return result;
}

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

@Override
public <T extends DataObject> CheckedFuture<Void, DTxException> putAndRollbackOnFailure(
        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  a 2s . c  o  m*/
    Preconditions.checkArgument(containsIid(nodeId), "Unknown node: %s. Not in transaction", nodeId);
    CheckedFuture<Void, DTxException> putFuture = transaction.asyncPut(logicalDatastoreType, instanceIdentifier,
            t);

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

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

        @Override
        public void onFailure(Throwable throwable) {
            LOG.trace("asyncput failure callback begin to roll back ");
            Runnable rolllbackRoutine = new Runnable() {
                @Override
                public void run() {
                    CheckedFuture<Void, DTxException.RollbackFailedException> rollExcept = rollback();

                    Futures.addCallback(rollExcept, new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void result) {
                            dtxReleaseDevices();
                            retFuture.setException(new DTxException.EditFailedException(
                                    "Failed to put but succeed to rollback"));
                        }

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

            new Thread(rolllbackRoutine).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("Put failed and rollback failure", e);
        }
    });
}

From source file:com.google.devcoin.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 ww.j av a 2  s .c  o m
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
    checkNotNull(memoryPool, "Must have a configured MemoryPool object to download dependencies.");
    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:com.microsoft.services.sharepoint.ListClient.java

/**
 * Insert list item./*  w w  w .  ja v  a  2 s .c  om*/
 *
 * @param listItem the list item
 * @param list the list
 * @return the office future
 */
public ListenableFuture<Void> insertListItem(final SPListItem listItem, final SPList list) {
    final SettableFuture<Void> result = SettableFuture.create();

    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/Items";
    getListUrl = String.format(getListUrl, urlEncode(list.getTitle()));

    try {
        JSONObject payload = new JSONObject();
        JSONObject metadata = new JSONObject();
        metadata.put("type", list.getListItemEntityTypeFullName());
        payload.put("__metadata", metadata);

        for (String key : listItem.getValues().keySet()) {

            Object object = listItem.getValues().get(key);
            // we assume you're trying to store a value on a linked
            // sharepoint list
            if (object instanceof JSONArray) {
                JSONObject container = new JSONObject();
                container.put("results", object);
                payload.put(key + "Id", container);
            } else {
                payload.put(key, object);
            }
        }

        ListenableFuture<JSONObject> request = executeRequestJsonWithDigest(getListUrl, "POST", null,
                getBytes(payload.toString()));

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

            @Override
            public void onSuccess(JSONObject json) {
                result.set(null);
            }
        });
    } catch (Throwable t) {
        result.setException(t);
    }

    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceTableBase.java

/**
 * Deletes an entity from a Mobile Service Table using a given id
 *
 * @param id         The id of the entity to delete
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 *//*from  w w  w.  j a  v  a  2s. co m*/
public ListenableFuture<Void> delete(String id, List<Pair<String, String>> parameters) {

    validateId(id);

    // Create delete request
    ServiceFilterRequest delete;

    Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon();
    uriBuilder.path(TABLES_URL);
    uriBuilder.appendPath(mTableName);
    uriBuilder.appendPath(id);

    EnumSet<MobileServiceFeatures> features = mFeatures.clone();
    if (parameters != null && parameters.size() > 0) {
        features.add(MobileServiceFeatures.AdditionalQueryParameters);
    }

    parameters = addSystemProperties(mSystemProperties, parameters);

    if (parameters != null && parameters.size() > 0) {
        for (Pair<String, String> parameter : parameters) {
            uriBuilder.appendQueryParameter(parameter.first, parameter.second);
        }
    }

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

    delete = new ServiceFilterRequestImpl(new HttpDelete(uriBuilder.build().toString()),
            mClient.getAndroidHttpClientFactory());
    if (!features.isEmpty()) {
        delete.addHeader(MobileServiceHttpClient.X_ZUMO_FEATURES,
                MobileServiceFeatures.featuresToString(features));
    }

    // Create AsyncTask to execute the request
    new RequestAsyncTask(delete, mClient.createConnection()) {
        @Override
        protected void onPostExecute(ServiceFilterResponse result) {
            if (mTaskException == null) {
                future.set(null);
            } else {
                future.setException(transformHttpException(mTaskException));
            }
        }
    }.executeTask();

    return future;
}

From source file:org.attribyte.api.http.impl.ning.NingClient.java

@Override
public ListenableFuture<org.attribyte.api.http.Response> asyncSend(final org.attribyte.api.http.Request request,
        final RequestOptions options) {

    final SettableFuture<org.attribyte.api.http.Response> fut = SettableFuture.create();

    try {/*from   ww  w . j ava2 s . c  o m*/
        httpClient.executeRequest(toNingRequest(request, options), new AsyncCompletionHandler<Response>() {
            @Override
            public Response onCompleted(Response response) throws Exception {
                ResponseBuilder builder = new ResponseBuilder();
                builder.setStatusCode(response.getStatusCode());
                Set<Map.Entry<String, List<String>>> entries = response.getHeaders().entrySet();
                for (Map.Entry<String, List<String>> header : entries) {
                    builder.addHeader(header.getKey(), header.getValue().get(0));
                }
                InputStream is = response.getResponseBodyAsStream();
                if (is != null) {
                    try {
                        builder.setBody(org.attribyte.api.http.Request.bodyFromInputStream(is,
                                options.maxResponseBytes));
                    } finally {
                        try {
                            is.close();
                        } catch (IOException ioe) {
                            //TODO
                        }
                    }
                }
                fut.set(builder.create());
                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                fut.setException(t);
            }
        });
    } catch (Throwable t) {
        fut.setException(t);
    }

    return fut;
}

From source file:io.crate.executor.transport.task.elasticsearch.QueryThenFetchPageableTaskResult.java

private ListenableFuture<PageableTaskResult> fetchWithNewQTF(final PageInfo pageInfo) {
    final SettableFuture<PageableTaskResult> future = SettableFuture.create();
    QueryThenFetchNode oldNode = ctx.searchNode();
    Futures.addCallback(operation.execute(oldNode, ctx.outputs(), Optional.of(pageInfo)),
            new FutureCallback<QueryThenFetchOperation.QueryThenFetchContext>() {
                @Override/*from   w  w w.  ja  v a  2 s  . c  o m*/
                public void onSuccess(@Nullable final QueryThenFetchOperation.QueryThenFetchContext newCtx) {
                    Futures.addCallback(newCtx.createSearchResponse(),
                            new FutureCallback<InternalSearchResponse>() {
                                @Override
                                public void onSuccess(@Nullable InternalSearchResponse searchResponse) {
                                    ObjectArray<Object[]> pageSource = newCtx
                                            .toPage(searchResponse.hits().hits(), extractors);
                                    newCtx.cleanAfterFirstPage();
                                    future.set(new QueryThenFetchPageableTaskResult(operation, newCtx,
                                            extractors, pageInfo, pageSource, 0L));
                                    closeSafe(); // close old searchcontexts and stuff
                                }

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

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

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

public <T extends DataObject> CheckedFuture<Void, DTxException> asyncMerge(
        final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<T> instanceIdentifier,
        final T t) {
    increaseOperation();/*from   w  w w .jav a2 s.com*/
    CheckedFuture<Optional<T>, ReadFailedException> readFuture = null;
    try {
        readFuture = delegate.read(logicalDatastoreType, instanceIdentifier);
    } catch (Exception e) {
        readFuture = Futures
                .immediateFailedCheckedFuture(new ReadFailedException("Read exception in merge action"));
    }

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

    Futures.addCallback(readFuture, new FutureCallback<Optional<T>>() {
        @Override
        public void onSuccess(final Optional<T> result) {
            synchronized (this) {
                cache.add(new CachedData(logicalDatastoreType, instanceIdentifier, result.orNull(),
                        ModifyAction.MERGE));
            }

            final ListeningExecutorService executorService = MoreExecutors
                    .listeningDecorator(executorPoolPerCache);
            final ListenableFuture asyncMergeFuture = executorService.submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    delegate.merge(logicalDatastoreType, instanceIdentifier, t);
                    return null;
                }
            });

            Futures.addCallback(asyncMergeFuture, new FutureCallback() {
                @Override
                public void onSuccess(@Nullable Object result) {
                    decreaseOperation();
                    retFuture.set(null);
                }

                @Override
                public void onFailure(Throwable t) {
                    decreaseOperation();
                    LOG.trace("async merge failure");
                    retFuture.setException(new DTxException.EditFailedException("async merge failure", t));
                }
            });
        }

        @Override
        public void onFailure(final Throwable t) {
            decreaseOperation();
            retFuture.setException(
                    new DTxException.ReadFailedException("failed to read from node in merge action", t));
        }
    });

    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 operation failed", e);
        }
    });
}

From source file:com.google.monacoin.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>
 *//*w  w w.  j  a v  a 2 s  .  c o  m*/
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
    checkNotNull(memoryPool, "Must have a configured MemoryPool object to download dependencies.");
    TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
    Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
    log.info("{}: Downloading dependencies of {}", getAddress(), 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 ignored) {
            resultFuture.set(results);
        }

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