List of usage examples for com.google.common.util.concurrent SettableFuture get
@Override public V get() throws InterruptedException, ExecutionException
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 w w w .ja v a 2 s.co m*/ 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:eu.esdihumboldt.hale.io.haleconnect.internal.HaleConnectServiceImpl.java
/** * @see eu.esdihumboldt.hale.io.haleconnect.HaleConnectService#uploadProjectFile(java.lang.String, * eu.esdihumboldt.hale.io.haleconnect.Owner, java.io.File, * eu.esdihumboldt.hale.common.core.io.ProgressIndicator) *//*from w ww . ja v a 2 s .c o m*/ @Override public boolean uploadProjectFile(String projectId, Owner owner, File file, ProgressIndicator progress) throws HaleConnectException { if (!this.isLoggedIn()) { throw new HaleConnectException("Not logged in"); } String apiKey = this.getSession().getToken(); SettableFuture<Boolean> future = SettableFuture.create(); try { FilesApi filesApi = ProjectStoreHelper.getFilesApi(this, apiKey); // POST /raw int totalWork = computeTotalWork(file); ApiCallback<Feedback> apiCallback = createUploadFileCallback(future, progress, file, totalWork); progress.begin("Uploading project archive", totalWork); filesApi.addFilesAsync(owner.getType().getJsonValue(), owner.getId(), projectId, file, apiCallback); return future.get(); } catch (com.haleconnect.api.projectstore.v1.ApiException e1) { throw new HaleConnectException(e1.getMessage(), e1, e1.getCode(), e1.getResponseHeaders()); } catch (ExecutionException e2) { Throwable t = e2.getCause(); if (t instanceof HaleConnectException) { throw (HaleConnectException) t; } else { throw new HaleConnectException(t.getMessage(), t); } } catch (InterruptedException e3) { throw new HaleConnectException(e3.getMessage(), e3); } }
From source file:io.v.syncbase.Database.java
/** * Notifies {@code h} of any existing syncgroup invites, and of all subsequent new invites. *//* ww w . j a v a 2 s . c o m*/ public void addSyncgroupInviteHandler(final SyncgroupInviteHandler h, AddSyncgroupInviteHandlerOptions opts) { synchronized (mSyncgroupInviteHandlersMu) { try { long scanId = io.v.syncbase.internal.Database.SyncgroupInvitesNewScan(getId().encode(), new io.v.syncbase.internal.Database.SyncgroupInvitesCallbacks() { @Override public void onInvite(final io.v.syncbase.core.SyncgroupInvite invite) { final SettableFuture<Boolean> setFuture = SettableFuture.create(); Syncbase.sOpts.mCallbackExecutor.execute(new Runnable() { @Override public void run() { h.onInvite(new SyncgroupInvite(new Id(invite.syncgroup), invite.blessingNames)); setFuture.set(true); } }); try { setFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); System.err.println(e.toString()); } } }); mSyncgroupInviteHandlers.put(h, scanId); } catch (VError vError) { h.onError(vError); } } }
From source file:org.usrz.libs.utils.concurrent.SimpleExecutor.java
public <T> NotifyingFuture<T> call(Callable<T> callable) { final SettableFuture<T> settableFuture = SettableFuture.create(); final Future<T> executingFuture = executor.submit(() -> { try {//from w w w .jav a 2 s . c om final T result = callable.call(); settableFuture.set(result); return result; } catch (Throwable throwable) { settableFuture.setException(throwable); throw new Exception(throwable); } }); return new NotifyingFuture<T>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { if (executingFuture.cancel(mayInterruptIfRunning)) { settableFuture.cancel(mayInterruptIfRunning); return true; } else { return false; } } @Override public boolean isCancelled() { return settableFuture.isCancelled(); } @Override public boolean isDone() { return settableFuture.isCancelled(); } @Override public T get() throws InterruptedException, ExecutionException { return settableFuture.get(); } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return settableFuture.get(timeout, unit); } @Override public NotifyingFuture<T> withConsumer(Consumer<Future<T>> consumer) { settableFuture.addListener(() -> consumer.accept(settableFuture), notifier); return this; } }; }
From source file:com.continuuity.weave.internal.ServiceMain.java
protected final void doMain(final Service service) throws ExecutionException, InterruptedException { configureLogger();/*from www.j ava 2 s . c o m*/ final String serviceName = service.getClass().getName(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info("Shutdown hook triggered. Shutting down service " + serviceName); service.stopAndWait(); LOG.info("Service shutdown " + serviceName); } }); // Listener for state changes of the service final SettableFuture<Service.State> completion = SettableFuture.create(); service.addListener(new Service.Listener() { @Override public void starting() { LOG.info("Starting service " + serviceName); } @Override public void running() { LOG.info("Service running " + serviceName); } @Override public void stopping(Service.State from) { LOG.info("Stopping service " + serviceName + " from " + from); } @Override public void terminated(Service.State from) { LOG.info("Service terminated " + serviceName + " from " + from); completion.set(from); } @Override public void failed(Service.State from, Throwable failure) { LOG.info("Service failure " + serviceName, failure); completion.setException(failure); } }, Threads.SAME_THREAD_EXECUTOR); // Starts the service service.start(); try { // If container failed with exception, the future.get() will throws exception completion.get(); } finally { // ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); // if (loggerFactory instanceof LoggerContext) { // ((LoggerContext) loggerFactory).stop(); // } } }
From source file:co.cask.cdap.internal.app.runtime.distributed.AbstractProgramTwillRunnable.java
@Override public void run() { LOG.info("Starting metrics service"); Futures.getUnchecked(Services.chainStart(zkClientService, kafkaClientService, metricsCollectionService, streamCoordinatorClient, resourceReporter)); LOG.info("Starting runnable: {}", name); controller = injector.getInstance(getProgramClass()).run(program, programOpts); final SettableFuture<ProgramController.State> state = SettableFuture.create(); controller.addListener(new AbstractListener() { @Override/*w w w .jav a 2 s . c o m*/ public void alive() { runlatch.countDown(); } @Override public void init(ProgramController.State currentState, @Nullable Throwable cause) { if (currentState == ProgramController.State.ALIVE) { alive(); } else { super.init(currentState, cause); } } @Override public void completed() { state.set(ProgramController.State.COMPLETED); } @Override public void killed() { state.set(ProgramController.State.KILLED); } @Override public void error(Throwable cause) { LOG.error("Program runner error out.", cause); state.setException(cause); } }, MoreExecutors.sameThreadExecutor()); try { state.get(); LOG.info("Program stopped."); } catch (InterruptedException e) { LOG.warn("Program interrupted.", e); } catch (ExecutionException e) { LOG.error("Program execution failed.", e); if (propagateServiceError()) { throw Throwables.propagate(Throwables.getRootCause(e)); } } finally { // Always unblock the handleCommand method if it is not unblocked before (e.g if program failed to start). // The controller state will make sure the corresponding command will be handled correctly in the correct state. runlatch.countDown(); } }
From source file:org.apache.storm.cassandra.trident.state.TridentAyncCQLResultSetValuesMapper.java
@Override public List<List<Values>> map(Session session, List<Statement> statements, final List<ITuple> tuples) { AsyncExecutor<Integer> executor = AsyncExecutorProvider.getLocal(session, AsyncResultHandler.NO_OP_HANDLER); final List<Integer> indexes = new ArrayList<>(); final List<List<Values>> results = new ArrayList<>(); for (int i = 0; i < statements.size(); i++) { indexes.add(i);// w ww .jav a 2s .c om results.add(null); } SettableFuture<List<Integer>> result = executor.execAsync(statements, indexes, throttle, new AsyncResultSetHandler<Integer>() { @Override public void success(Integer index, ResultSet resultSet) { if (outputDeclaredFields != null) { List<Values> thisResult = new ArrayList<>(); for (Row row : resultSet) { final Values values = new Values(); for (String field : outputDeclaredFields) { ITuple tuple = tuples.get(index); if (tuple.contains(field)) { values.add(tuple.getValueByField(field)); } else { values.add(row.getObject(field)); } } thisResult.add(values); } results.set(index, thisResult); } } @Override public void failure(Throwable t, Integer index) { // Exceptions are captured and thrown at the end of the batch by the executor } }); try { // Await all results result.get(); } catch (Exception e) { throw new FailedException(e.getMessage(), e); } return results; }
From source file:com.microsoft.alm.plugin.idea.tfvc.core.TFSVcs.java
private void checkCommandLineVersion() { if (hasVersionBeenVerified) { // No need to check the version again if we have already checked it once this session logger.info("Skipping the attempt to check the version of the TF command line."); return;/*from www . j av a2s . c o m*/ } hasVersionBeenVerified = true; // We want to start a background thread to check the version, but that can only be done // form the UI thread. IdeaHelper.runOnUIThread(new Runnable() { @Override public void run() { final SettableFuture<String> versionMessage = SettableFuture.create(); (new Task.Backgroundable(getProject(), TfPluginBundle.message(TfPluginBundle.KEY_TFVC_TF_VERSION_WARNING_PROGRESS), false, PerformInBackgroundOption.ALWAYS_BACKGROUND) { public void run(@NotNull final ProgressIndicator indicator) { try { logger.info("Attempting to check the version of the TF command line."); TfTool.checkVersion(); versionMessage.set(StringUtils.EMPTY); } catch (final ToolException ex) { final String error = LocalizationServiceImpl.getInstance().getExceptionMessage(ex); logger.warn(error); versionMessage.set(error); } catch (final Throwable t) { // Don't let unknown errors bubble out here logger.warn("Unexpected error when checking the version of the command line.", t); } } public void onSuccess() { try { final String error = versionMessage.get(); if (StringUtils.isNotEmpty(error)) { logger.info("Notifying the user of the min version problem."); // Notify the user that they should upgrade their version of the TF command line VcsNotifier.getInstance(getProject()).notifyImportantWarning( TfPluginBundle.message(TfPluginBundle.KEY_TFVC_TF_VERSION_WARNING_TITLE), error, new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent hyperlinkEvent) { if (SETTINGS_URL_EVENT.equals(hyperlinkEvent.getDescription())) { ShowSettingsUtil.getInstance().showSettingsDialog(myProject, getConfigurable().getDisplayName()); } else if (HELP_URL_EVENT.equals(hyperlinkEvent.getDescription())) { BrowserUtil.browse(TFVC_ONLINE_HELP_URL); } else { logger.warn("Unknown hyperlinkEvent triggered: " + hyperlinkEvent.getDescription()); } } }); } } catch (Exception e) { logger.warn("Failed to warn user about min version of TF command line.", e); } } }).queue(); } }); }
From source file:com.google.pubsub.flic.controllers.Client.java
void start(MessageTracker messageTracker) throws Throwable { this.messageTracker = messageTracker; // Send a gRPC call to start the server log.info("Connecting to " + networkAddress + ":" + PORT); StartRequest.Builder requestBuilder = StartRequest.newBuilder().setProject(project).setTopic(topic) .setMaxOutstandingRequests(maxOutstandingRequests).setMessageSize(messageSize) .setRequestRate(requestRate).setStartTime(startTime).setPublishBatchSize(publishBatchSize); if (numberOfMessages > 0) { requestBuilder.setNumberOfMessages(numberOfMessages); } else {/*w w w . java 2s.c om*/ requestBuilder.setTestDuration(Duration.newBuilder().setSeconds(loadtestLengthSeconds).build()); } switch (clientType) { case CPS_GCLOUD_JAVA_SUBSCRIBER: requestBuilder.setPubsubOptions(PubsubOptions.newBuilder().setSubscription(subscription) .setMaxMessagesPerPull(maxMessagesPerPull)); break; case KAFKA_PUBLISHER: requestBuilder.setKafkaOptions(KafkaOptions.newBuilder().setBroker(broker)); break; case KAFKA_SUBSCRIBER: requestBuilder.setKafkaOptions(KafkaOptions.newBuilder().setBroker(broker).setPollLength(pollLength)); break; case CPS_GCLOUD_JAVA_PUBLISHER: case CPS_GCLOUD_PYTHON_PUBLISHER: break; } StartRequest request = requestBuilder.build(); SettableFuture<Void> startFuture = SettableFuture.create(); stub = getStub(); stub.start(request, new StreamObserver<StartResponse>() { private int connectionErrors = 0; @Override public void onNext(StartResponse response) { log.info("Successfully started client [" + networkAddress + "]"); clientStatus = ClientStatus.RUNNING; startFuture.set(null); } @Override public void onError(Throwable throwable) { if (connectionErrors > 10) { log.error("Client failed to start " + connectionErrors + " times, shutting down."); clientStatus = ClientStatus.FAILED; startFuture.setException(throwable); doneFuture.setException(throwable); return; } connectionErrors++; try { Thread.sleep(5000); } catch (InterruptedException e) { log.info("Interrupted during back off, retrying."); } log.debug("Going to retry client connection, likely due to start up time."); stub = getStub(); stub.start(request, this); } @Override public void onCompleted() { } }); try { startFuture.get(); executorService.scheduleAtFixedRate(this::checkClient, 20, 20, TimeUnit.SECONDS); } catch (ExecutionException e) { throw e.getCause(); } }
From source file:io.v.syncbase.Database.java
/** * Notifies {@code h} of initial state, and of all subsequent changes to this database. *//*from w w w . j a v a 2s.c o m*/ public void addWatchChangeHandler(final WatchChangeHandler h, final AddWatchChangeHandlerOptions opts) { // Note: Eventually we'll add a watch variant that takes a query, where the query can be // constructed using some sort of query builder API. // TODO(sadovsky): Support specifying resumeMarker. Note, watch-from-resumeMarker may be // problematic in that we don't track the governing ACL for changes in the watch log. if (opts.resumeMarker != null && opts.resumeMarker.length != 0) { throw new UnsupportedOperationException("Specifying resumeMarker is not yet supported"); } final AtomicBoolean canceled = new AtomicBoolean(false); mCoreDatabase.watch(null, ImmutableList.of(opts.getCollectionRowPattern()), new io.v.syncbase.core.Database.WatchPatternsCallbacks() { private boolean mGotFirstBatch = false; private final List<WatchChange> mBatch = new ArrayList<>(); @Override public void onChange(io.v.syncbase.core.WatchChange coreWatchChange) { if (canceled.get()) { return; } boolean isRoot = coreWatchChange.entityType == io.v.syncbase.core.WatchChange.EntityType.ROOT; boolean isUserdataInternalRow = coreWatchChange.entityType == io.v.syncbase.core.WatchChange.EntityType.ROW && coreWatchChange.collection.name.equals(Syncbase.USERDATA_NAME) && coreWatchChange.row.startsWith(Syncbase.USERDATA_INTERNAL_PREFIX); if (!isRoot && (opts.showUserdataInternalRow || !isUserdataInternalRow)) { mBatch.add(new WatchChange(coreWatchChange)); } if (!coreWatchChange.continued) { final SettableFuture<Boolean> setFuture = SettableFuture.create(); if (!mGotFirstBatch) { mGotFirstBatch = true; final List<WatchChange> cpBatch = mBatch; Syncbase.sOpts.mCallbackExecutor.execute(new Runnable() { @Override public void run() { h.onInitialState(cpBatch.iterator()); setFuture.set(true); } }); } else { final List<WatchChange> cpBatch = mBatch; Syncbase.sOpts.mCallbackExecutor.execute(new Runnable() { @Override public void run() { h.onChangeBatch(cpBatch.iterator()); setFuture.set(true); } }); } try { setFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); System.err.println(e.toString()); } mBatch.clear(); } } @Override public void onError(VError vError) { // TODO(sadovsky): Make sure cancellations are surfaced as such (or ignored). h.onError(vError); } }); synchronized (mWatchChangeHandlersMu) { mWatchChangeHandlers.put(h, new Runnable() { @Override public void run() { // TODO(alexfandrianto): Implement properly. AtomicBoolean is only a patch. canceled.set(true); } }); } }