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.table.sync.MobileServiceJsonSyncTable.java

/**
 * Delete an item from the local table and enqueue the operation to be
 * synchronized on context push.// ww  w. j  a v a 2s . com
 *
 * @param item the item to be deleted
 * @return A ListenableFuture that is done when the item has been deleted.
 */
public ListenableFuture<Void> delete(final JsonObject item) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<Void> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                thisTable.deleteContext(item);

                result.set(null);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

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

/**
 * Delete an item from the local table and enqueue the operation to be
 * synchronized on context push.//w w  w .  j a v  a  2s.c  o m
 *
 * @param itemId the id of the item to be deleted
 * @return A ListenableFuture that is done when the item has been deleted.
 */
public ListenableFuture<Void> delete(final String itemId) {
    final MobileServiceJsonSyncTable thisTable = this;
    final SettableFuture<Void> result = SettableFuture.create();

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                thisTable.deleteContext(itemId);

                result.set(null);
            } catch (Throwable throwable) {
                result.setException(throwable);
            }
        }
    }).start();

    return result;
}

From source file:com.microsoftopentechnologies.intellij.helpers.azure.sdk.AzureSDKManagerImpl.java

@NotNull
private static ListenableFuture<StorageAccount> getStorageAccountAsync(@NotNull final String subscriptionId,
        @NotNull final StorageManagementClient client,
        @NotNull final com.microsoft.windowsazure.management.storage.models.StorageAccount storageAccount)
        throws Exception {
    final SettableFuture<StorageAccount> future = SettableFuture.create();

    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
        @Override//from  w w  w.j  a va2s .  c o  m
        public void run() {
            try {
                future.set(getStorageAccount(subscriptionId, client, storageAccount));
            } catch (Exception e) {
                future.setException(e);
            }
        }
    });

    return future;
}

From source file:io.v.v23.rpc.ReflectInvoker.java

@Override
public ListenableFuture<Object[]> invoke(final VContext ctx, final StreamServerCall call, final String method,
        final Object[] args) {
    Executor executor = V.getExecutor(ctx);
    if (executor == null) {
        return Futures.immediateFailedFuture(new VException("NULL executor in context: did "
                + "you derive server context from the context returned by V.init()?"));
    }//from   ww  w.ja  va  2  s  . c  om
    try {
        final ServerMethod m = findMethod(method);
        final SettableFuture<ListenableFuture<Object[]>> ret = SettableFuture.create();
        // Invoke the method.
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (ctx.isCanceled()) {
                        ret.setException(new CanceledException(ctx));
                        return;
                    }
                    // Invoke the method and process results.
                    Object[] allArgs = new Object[2 + args.length];
                    allArgs[0] = ctx;
                    allArgs[1] = call;
                    System.arraycopy(args, 0, allArgs, 2, args.length);
                    Object result = m.invoke(allArgs);
                    ret.set(prepareReply(m, result));
                } catch (InvocationTargetException | IllegalAccessException e) {
                    ret.setException(new VException(
                            String.format("Error invoking method %s: %s", method, e.getCause().toString())));
                }
            }
        });
        return Futures.dereference(ret);
    } catch (VException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:org.apache.bookkeeper.stream.segment.BKSegmentWriter.java

private void write0(Record record, SettableFuture<SSN> future) {
    if (inErrorState) {
        if (pendingEntries.isEmpty()) {
            future.setException(
                    new WriteCancelledException("Writing record cancelled because segment " + segmentName + "@"
                            + streamName + " is already in error state : bk result = " + lastBkResult));
        } else {// w  w  w  . j a  v a2  s.  c  o m
            errorQueue.add(future);
        }
        return;
    }

    if (State.CLOSING == state || State.CLOSED == state) {
        if (pendingEntries.isEmpty()) {
            future.setException(new WriteCancelledException("Writing record cancelled because segment "
                    + segmentName + "@" + streamName + " is closed : bk result = " + lastBkResult));
        } else {
            errorQueue.add(future);
        }
        return;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Adding record {} to segment {} @ {}", new Object[] { record, segmentName, streamName });
    }

    try {
        curEntryBuilder.addRecord(record, future);
    } catch (IOException ioe) {
        logger.error("Encountered unexpected exception on adding record {} to {}@{} : ",
                new Object[] { record, segmentName, streamName, ioe });
        inErrorState = true;
        if (pendingEntries.isEmpty()) {
            WriteCancelledException wce = new WriteCancelledException(
                    "Writing record cancelled because segment " + segmentName + "@" + streamName
                            + " encountered exception on current entry : ",
                    ioe);
            cancelCurrentEntry(wce);
            future.setException(wce);
        } else {
            Entry entry = curEntryBuilder.asDataEntry().build();
            List<SettableFuture<SSN>> futureList = entry.getRecordFutureList().get();
            errorQueue.addAll(futureList);
            errorQueue.add(future);
            curEntryBuilder = null;
        }
        return;
    }
    flushIfNeeded();
}

From source file:io.crate.action.sql.DDLAnalysisDispatcher.java

private ListenableFuture<Long> wrapRowCountFuture(ListenableFuture<?> wrappedFuture, final Long rowCount) {
    final SettableFuture<Long> wrappingFuture = SettableFuture.create();
    Futures.addCallback(wrappedFuture, new FutureCallback<Object>() {
        @Override//from   w  w  w  .j a v  a 2s  .  co m
        public void onSuccess(@Nullable Object result) {
            wrappingFuture.set(rowCount);
        }

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

From source file:com.spotify.futures.AsyncRetrier.java

private <T> void handleFailure(final SettableFuture<T> future, final Supplier<ListenableFuture<T>> code,
        final int retries, final long delay, final TimeUnit timeUnit, final Predicate<T> retryCondition,
        Throwable t) {/*from ww w . ja v  a 2 s  . co m*/
    if (retries > 0) {
        if (delay > 0) {
            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    startRetry(future, code, retries - 1, delay, timeUnit, retryCondition);
                }
            }, delay, timeUnit);
        } else {
            startRetry(future, code, retries - 1, delay, timeUnit, retryCondition);
        }
    } else {
        future.setException(t);
    }
}

From source file:org.robotninjas.barge.state.ReplicaManager.java

private ListenableFuture<AppendEntriesResponse> sendUpdate() {

    running++;/*from  w w  w  .  ja v a 2 s  .  c  o m*/
    requested = false;

    // if the last rpc call was successful then try to send
    // as many updates as we can, otherwise, if we're
    // probing backwards, only send one entry as a probe, as
    // soon as we have a successful call forwards will become
    // true and we can catch up quickly
    GetEntriesResult result = log.getEntriesFrom(nextIndex, forwards ? BATCH_SIZE : 1);

    final AppendEntries request = AppendEntries.newBuilder().setTerm(log.currentTerm())
            .setLeaderId(log.self().toString()).setPrevLogIndex(result.lastLogIndex())
            .setPrevLogTerm(result.lastLogTerm()).setCommitIndex(log.commitIndex())
            .addAllEntries(result.entries()).build();

    LOGGER.debug("Sending update to {} prevLogIndex {} prevLogTerm {}", remote, result.lastLogIndex(),
            result.lastLogTerm());
    final ListenableFuture<AppendEntriesResponse> response = client.appendEntries(remote, request);

    final SettableFuture<AppendEntriesResponse> previousResponse = nextResponse;

    Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {

        @Override
        public void onSuccess(@Nullable AppendEntriesResponse result) {
            running--;
            updateNextIndex(request, result);
            if (result.getSuccess()) {
                previousResponse.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            running--;
            requested = false;
            previousResponse.setException(t);
        }

    });

    nextResponse = SettableFuture.create();

    return response;

}

From source file:io.crate.blob.v2.BlobIndices.java

public ListenableFuture<Void> dropBlobTable(final String tableName) {
    final SettableFuture<Void> result = SettableFuture.create();
    transportDeleteIndexActionProvider.get().execute(new DeleteIndexRequest(fullIndexName(tableName)),
            new ActionListener<DeleteIndexResponse>() {
                @Override/*from  w ww .j  av a2s .com*/
                public void onResponse(DeleteIndexResponse deleteIndexResponse) {
                    result.set(null);
                }

                @Override
                public void onFailure(Throwable e) {
                    result.setException(e);
                }
            });
    return result;
}

From source file:com.microsoft.assetmanagement.files.SharepointListsClientWithFiles.java

/**
 * Gets the SP file from picture library.
 * //from w ww . j a  v  a  2 s  .  c  o m
 * @param library
 *            the library
 * @param id
 *            the id
 * @return the SP file from picture library
 */
public ListenableFuture<SPFile> getSPFileFromPictureLibrary(final String library, final String id) {

    final SettableFuture<SPFile> result = SettableFuture.create();
    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')/items('%s')/File";
    getListUrl = String.format(getListUrl, urlEncode(library), id);

    try {
        ListenableFuture<JSONObject> request = executeRequestJson(getListUrl, "GET");
        Futures.addCallback(request, new FutureCallback<JSONObject>() {
            @Override
            public void onFailure(Throwable t) {
                result.setException(t);
            }

            @Override
            public void onSuccess(JSONObject json) {
                SPFile file = new SPFile();
                file.loadFromJson(json);
                result.set(file);
            }
        });

    } catch (Throwable t) {
        result.setException(t);
    }
    return result;
}