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.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionService.java

@Override
public ExecutionResult execute(Protocol.Digest actionDigest) throws IOException, InterruptedException {
    SettableFuture<Operation> future = SettableFuture.create();

    getStubWithTraceInfo(actionDigest).execute(
            ExecuteRequest.newBuilder().setInstanceName(instanceName)
                    .setActionDigest(GrpcProtocol.get(actionDigest)).setSkipCacheLookup(false).build(),
            new StreamObserver<Operation>() {
                @Nullable//from   ww w  . ja va2  s .  com
                Operation op = null;

                @Override
                public void onNext(Operation value) {
                    op = value;
                }

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

                @Override
                public void onCompleted() {
                    future.set(op);
                }
            });

    try {
        Operation operation = future.get();
        if (operation.hasError()) {
            throw new RuntimeException("Execution failed: " + operation.getError().getMessage());
        }

        if (!operation.hasResponse()) {
            throw new RuntimeException("Invalid operation response: missing ExecutionResponse object");
        }

        ActionResult actionResult = operation.getResponse().unpack(ExecuteResponse.class).getResult();
        return new ExecutionResult() {
            @Override
            public List<OutputDirectory> getOutputDirectories() {
                return actionResult.getOutputDirectoriesList().stream().map(GrpcOutputDirectory::new)
                        .collect(Collectors.toList());
            }

            @Override
            public List<OutputFile> getOutputFiles() {
                return actionResult.getOutputFilesList().stream().map(GrpcOutputFile::new)
                        .collect(Collectors.toList());
            }

            @Override
            public int getExitCode() {
                return actionResult.getExitCode();
            }

            @Override
            public Optional<String> getStderr() {
                ByteString stderrRaw = actionResult.getStderrRaw();
                if (stderrRaw == null
                        || (stderrRaw.isEmpty() && actionResult.getStderrDigest().getSizeBytes() > 0)) {
                    System.err.println("Got stderr digest.");
                    try {
                        ByteString data = ByteString.EMPTY;
                        GrpcRemoteExecutionClients.readByteStream(instanceName,
                                new GrpcDigest(actionResult.getStderrDigest()), byteStreamStub, data::concat)
                                .get();
                        return Optional.of(data.toStringUtf8());
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.err.println("Got raw stderr: " + stderrRaw.toStringUtf8());
                    return Optional.of(stderrRaw.toStringUtf8());
                }
            }
        };
    } catch (ExecutionException e) {
        Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
        Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
        e.printStackTrace();
        throw new BuckUncheckedExecutionException(e.getCause());
    }
}

From source file:com.microsoft.assetmanagement.AssetApplication.java

/**
 * Authenticate.//  w w  w.j  a  va  2  s.c  om
 * 
 * @param activity
 *            the activity
 * @return the office future
 */
public ListenableFuture<Credentials> authenticate(Activity activity) {
    final SettableFuture<Credentials> result = SettableFuture.create();

    String method = mPreferences.getAuthenticationMethod();
    if (method.equals(Constants.AUTHENTICATIONMETHOD_COOKIES)) {
        ListenableFuture<CookieCredentials> future = SharepointCookieCredentials
                .requestCredentials(mPreferences.getSharepointServer(), activity);

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

            @Override
            public void onSuccess(CookieCredentials credentials) {
                mCredentials = credentials;
                result.set(credentials);
            }
        });
    } else if (method.equals(Constants.AUTHENTICATIONMETHOD_AAD)) {
        getAuthenticationContext(activity).acquireToken(activity, mPreferences.getSharepointServer(),
                mPreferences.getClientId(), mPreferences.getRedirectUrl(), PromptBehavior.Auto,

                new AuthenticationCallback<AuthenticationResult>() {

                    @Override
                    public void onSuccess(AuthenticationResult authenticationResult) {
                        // once succeeded we create a credentials instance
                        // using the token from ADAL
                        mCredentials = new OAuthCredentials(authenticationResult.getAccessToken());
                        result.set(mCredentials);
                    }

                    @Override
                    public void onError(Exception exc) {
                        result.setException(exc);
                    }
                });
    } else {
        String userName = mPreferences.getNTLMUser();
        String password = mPreferences.getNTLMPassword();
        mCredentials = new BasicAuthenticationCredentials(userName, password);
        result.set(mCredentials);
    }
    return result;
}

From source file:com.github.sparkfy.network.client.TransportClient.java

/**
 * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to
 * a specified timeout for a response.//from  ww w.j a  v  a  2 s  .c  o  m
 */
public ByteBuffer sendRpcSync(ByteBuffer message, long timeoutMs) {
    final SettableFuture<ByteBuffer> result = SettableFuture.create();

    sendRpc(message, new RpcResponseCallback() {
        @Override
        public void onSuccess(ByteBuffer response) {
            ByteBuffer copy = ByteBuffer.allocate(response.remaining());
            copy.put(response);
            // flip "copy" to make it readable
            copy.flip();
            result.set(copy);
        }

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

    try {
        return result.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

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

public ESBulkIndexTask(ClusterService clusterService, Settings settings,
        TransportShardBulkActionDelegate transportShardBulkActionDelegate,
        TransportCreateIndexAction transportCreateIndexAction, ESIndexNode node) {
    this.node = node;
    this.bulkShardProcessor = new BulkShardProcessor(clusterService, settings, transportShardBulkActionDelegate,
            transportCreateIndexAction, node.partitionedTable(), true, this.node.sourceMaps().size());

    if (!node.isBulkRequest()) {
        final SettableFuture<RowCountResult> futureResult = SettableFuture.create();
        resultList = new ArrayList<>(1);
        resultList.add(futureResult);/*from   w  ww. ja va  2s  .  co m*/

        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    futureResult.set(TaskResult.ROW_COUNT_UNKNOWN);
                } else {
                    futureResult.set(new RowCountResult(result.cardinality()));
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                futureResult.setException(t);
            }
        });
    } else {
        final int numResults = node.sourceMaps().size();
        resultList = new ArrayList<>(numResults);
        for (int i = 0; i < numResults; i++) {
            resultList.add(SettableFuture.<RowCountResult>create());
        }
        Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
            @Override
            public void onSuccess(@Nullable BitSet result) {
                if (result == null) {
                    setAllToFailed(null);
                    return;
                }

                for (int i = 0; i < numResults; i++) {
                    SettableFuture<RowCountResult> future = (SettableFuture<RowCountResult>) resultList.get(i);
                    future.set(result.get(i) ? TaskResult.ONE_ROW : TaskResult.FAILURE);
                }
            }

            private void setAllToFailed(@Nullable Throwable throwable) {
                if (throwable == null) {
                    for (ListenableFuture<RowCountResult> future : resultList) {
                        ((SettableFuture<RowCountResult>) future).set(TaskResult.FAILURE);
                    }
                } else {
                    for (ListenableFuture<RowCountResult> future : resultList) {
                        ((SettableFuture<RowCountResult>) future).set(RowCountResult.error(throwable));
                    }
                }
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                setAllToFailed(t);
            }
        });
    }
}

From source file:com.github.fhuss.storm.cassandra.executor.AsyncExecutor.java

/**
 * Asynchronously executes the specified batch statement. Inputs will be passed to
 * the {@link #handler} once query succeed or failed.
 *///from   w ww.  j  a v  a  2  s .c  o  m
public SettableFuture<T> execAsync(final Statement statement, final T inputs, AsyncResultHandler<T> handler) {
    final SettableFuture<T> settableFuture = SettableFuture.create();
    pending.put(settableFuture, true);
    ResultSetFuture future = session.executeAsync(statement);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        public void release() {
            pending.remove(settableFuture);
        }

        @Override
        public void onSuccess(ResultSet result) {
            release();
            settableFuture.set(inputs);
            handler.success(inputs);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error(String.format("Failed to execute statement '%s' ", statement), t);
            release();
            settableFuture.setException(t);
            handler.failure(t, inputs);
        }
    }, executorService);
    return settableFuture;
}

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

/**
 * Downloads a blob with content hash {@code digest} and stores its content in memory.
 *
 * @return a future that completes after the download completes (succeeds / fails). If successful,
 *     the content is stored in the future's {@code byte[]}.
 *///from ww  w.  j  a va 2 s  .c  om
public ListenableFuture<byte[]> downloadBlob(Digest digest) {
    if (digest.getSizeBytes() == 0) {
        return EMPTY_BYTES;
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream((int) digest.getSizeBytes());
    SettableFuture<byte[]> outerF = SettableFuture.create();
    Futures.addCallback(downloadBlob(digest, bOut), new FutureCallback<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            outerF.set(bOut.toByteArray());
        }

        @Override
        public void onFailure(Throwable t) {
            outerF.setException(t);
        }
    }, MoreExecutors.directExecutor());
    return outerF;
}

From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java

@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {

    LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);

    final Future<Boolean> existsFuture = delegate.exists(store, path);
    final SettableFuture<Boolean> settableFuture = SettableFuture.create();
    final CheckedFuture<Boolean, ReadFailedException> checkedFuture;
    checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() {
        @Nullable//ww w .  java  2  s .c  o m
        @Override
        public ReadFailedException apply(Exception cause) {
            return new ReadFailedException("Read from transaction failed", cause);
        }
    });
    existsFuture.onComplete(new OnComplete<Boolean>() {
        @Override
        public void onComplete(final Throwable throwable, final Boolean result) throws Throwable {
            if (throwable == null) {
                settableFuture.set(result);
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:org.copperengine.core.persistent.cassandra.CassandraStorage.java

private SettableFuture<Void> createSettableFuture(final ResultSetFuture rsf, final String mpId,
        final long startTsNanos) {
    final SettableFuture<Void> rv = SettableFuture.create();
    rsf.addListener(new Runnable() {
        @Override// ww  w  . j  a va  2s. c o  m
        public void run() {
            try {
                runtimeStatisticsCollector.submit(mpId, 1, System.nanoTime() - startTsNanos,
                        TimeUnit.NANOSECONDS);
                rsf.get();
                rv.set(null);
            } catch (InterruptedException e) {
                rv.setException(e);
            } catch (ExecutionException e) {
                rv.setException(e.getCause());
            }

        }
    }, executor);
    return rv;
}

From source file:com.microsoft.services.sharepoint.ListClient.java

/**
 * Gets the list items./*from   w w  w.  j ava 2s  . com*/
 *
 * @param listName the list name
 * @param query the query
 * @return the list items
 */
public ListenableFuture<List<SPListItem>> getListItems(String listName, Query query) {
    final SettableFuture<List<SPListItem>> result = SettableFuture.create();

    String listNamePart = String.format("_api/web/lists/GetByTitle('%s')/Items?", urlEncode(listName));
    String getListUrl = getSiteUrl() + listNamePart + generateODataQueryString(query);
    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) {
            try {
                result.set(SPListItem.listFromJson(json));
            } catch (JSONException e) {
                log(e);
            }
        }
    });

    return result;
}

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

/**
 * Upload file./* w w  w.  ja  va2s.  c  o m*/
 * 
 * @param documentLibraryName
 *            the document library name
 * @param fileName
 *            the file name
 * @param fileContent
 *            the file content
 * @return the office future
 */
public ListenableFuture<SPFile> uploadFile(final String documentLibraryName, final String fileName,
        final byte[] fileContent) {
    final SettableFuture<SPFile> result = SettableFuture.create();

    // The name of the library not always matches the title, here is how we
    // get the real path
    String getRootFolderUrl = getSiteUrl()
            + String.format("_api/web/lists/GetByTitle('%s')/RootFolder", urlEncode(documentLibraryName));

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

    Futures.addCallback(request, new FutureCallback<JSONObject>() {

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

        @Override
        public void onSuccess(JSONObject json) {
            try {

                String libraryServerRelativeUrl = json.getJSONObject("d").getString("ServerRelativeUrl");
                String getListUrl = getSiteUrl()
                        + "_api/web/GetFolderByServerRelativeUrl('%s')/Files/add(url='%s',overwrite=true)";
                getListUrl = String.format(getListUrl, urlEncode(libraryServerRelativeUrl),
                        urlEncode(fileName));

                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json;odata=verbose");
                ListenableFuture<JSONObject> request = executeRequestJsonWithDigest(getListUrl, "POST", headers,
                        fileContent);

                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;
}