Java Code Examples for com.google.common.util.concurrent.Futures#addCallback()

The following examples show how to use com.google.common.util.concurrent.Futures#addCallback() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HelloServiceTest.java    From armeria with Apache License 2.0 9 votes vote down vote up
@Test
void getReplyWithDelay() {
    final HelloServiceFutureStub helloService = Clients.newClient(uri(), HelloServiceFutureStub.class);
    final ListenableFuture<HelloReply> future =
            helloService.lazyHello(HelloRequest.newBuilder().setName("Armeria").build());
    final AtomicBoolean completed = new AtomicBoolean();
    Futures.addCallback(future, new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(HelloReply result) {
            assertThat(result.getMessage()).isEqualTo("Hello, Armeria!");
            completed.set(true);
        }

        @Override
        public void onFailure(Throwable t) {
            // Should never reach here.
            throw new Error(t);
        }
    }, MoreExecutors.directExecutor());

    await().untilTrue(completed);
}
 
Example 2
Source File: MobileServicePush.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Void> deleteInstallation() {
    final SettableFuture<Void> resultFuture = SettableFuture.create();

    String installationId = MobileServiceApplication.getInstallationId(mHttpClient.getClient().getContext());

    String path = PNS_API_URL + "/installations/" + Uri.encode(installationId);

    ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, null, HttpConstants.DeleteMethod, null, null);

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

        @Override
        public void onSuccess(ServiceFilterResponse response) {

            resultFuture.set(null);
        }
    }, MoreExecutors.directExecutor());

    return resultFuture;
}
 
Example 3
Source File: MobileServiceTable.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a query to retrieve all the table rows
 *
 * @param query    The MobileServiceQuery instance to execute
 * @param callback Callback to invoke when the operation is completed
 * @deprecated use {@link #execute( com.microsoft.windowsazure.mobileservices.table.query.Query query)} instead
 */
public void execute(Query query, final TableQueryCallback<E> callback) {
    ListenableFuture<MobileServiceList<E>> executeFuture = execute(query);

    Futures.addCallback(executeFuture, new FutureCallback<MobileServiceList<E>>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, 0, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, 0, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(MobileServiceList<E> result) {
            callback.onCompleted(result, result.size(), null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example 4
Source File: LoginManager.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Refreshes access token with the identity provider for the logged in user.
 * @param callback The callback to invoke when the authentication process finishes
 */
public void refreshUser(final UserAuthenticationCallback callback) {

    ListenableFuture<MobileServiceUser> future = refreshUser();

    Futures.addCallback(future, new FutureCallback<MobileServiceUser>() {
        @Override
        public void onSuccess(MobileServiceUser user) {
            callback.onCompleted(user, null, null);
        }

        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }
    }, MoreExecutors.directExecutor());
}
 
Example 5
Source File: ReloadConfig.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public static void execute(ManagerConnection c, final boolean loadAll) {
	
	// reload @@config_all 校验前一次的事务完成情况
	if ( loadAll && !NIOProcessor.backends_old.isEmpty() ) {
		c.writeErrMessage(ErrorCode.ER_YES, "The are several unfinished db transactions before executing \"reload @@config_all\", therefore the execution is terminated for logical integrity and please try again later.");
		return;
	}
	
	final ReentrantLock lock = MycatServer.getInstance().getConfig().getLock();		
	lock.lock();
	try {
		ListenableFuture<Boolean> listenableFuture = MycatServer.getInstance().getListeningExecutorService().submit(
			new Callable<Boolean>() {
				@Override
				public Boolean call() throws Exception {
					return loadAll ? reload_all() : reload();
				}
			}
		);
		Futures.addCallback(listenableFuture, new ReloadCallBack(c), MycatServer.getInstance().getListeningExecutorService());
	} finally {
		lock.unlock();
	}
}
 
Example 6
Source File: ProcessRuntime.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<InstanceCommunication.MetricsData> getMetrics(int instanceId) {
    CompletableFuture<InstanceCommunication.MetricsData> retval = new CompletableFuture<>();
    if (stub == null) {
        retval.completeExceptionally(new RuntimeException("Not alive"));
        return retval;
    }
    ListenableFuture<InstanceCommunication.MetricsData> response = stub.withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS).getMetrics(Empty.newBuilder().build());
    Futures.addCallback(response, new FutureCallback<InstanceCommunication.MetricsData>() {
        @Override
        public void onFailure(Throwable throwable) {
            retval.completeExceptionally(throwable);
        }

        @Override
        public void onSuccess(InstanceCommunication.MetricsData t) {
            retval.complete(t);
        }
    }, MoreExecutors.directExecutor());
    return retval;
}
 
Example 7
Source File: MobileServiceJsonTable.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Undeete an element from a Mobile Service Table
 *
 * @param element    The JsonObject to undelete
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 * @param callback   Callback to invoke when the operation is completed
 * @deprecated use {@link #update(com.google.gson.JsonObject element, List parameters)} instead
 */
public void undelete(final JsonObject element, List<Pair<String, String>> parameters, final TableJsonOperationCallback callback) {
    ListenableFuture<JsonObject> undeleteFuture = undelete(element, parameters);

    Futures.addCallback(undeleteFuture, new FutureCallback<JsonObject>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(JsonObject result) {
            callback.onCompleted(result, null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example 8
Source File: MobileServiceClient.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes Microsoft Azure Mobile Service authentication using a the Google
 * account registered in the device
 *
 * @param activity The activity that triggered the authentication
 * @param scopes   The scopes used as authentication token type for login
 * @param callback Callback to invoke when the authentication process finishes
 * @deprecated use {@link #loginWithGoogleAccount( android.app.Activity activity, String scopes)} instead
 */
public void loginWithGoogleAccount(Activity activity, String scopes, final UserAuthenticationCallback callback) {
    ListenableFuture<MobileServiceUser> loginFuture = loginWithGoogleAccount(activity, scopes);

    Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(MobileServiceUser user) {
            callback.onCompleted(user, null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example 9
Source File: ErrorHandlingClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
void futureCallCallback() {
  GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
  ListenableFuture<HelloReply> response =
      stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build());

  final CountDownLatch latch = new CountDownLatch(1);

  Futures.addCallback(
      response,
      new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(@Nullable HelloReply result) {
          // Won't be called, since the server in this example always fails.
        }

        @Override
        public void onFailure(Throwable t) {
          Status status = Status.fromThrowable(t);
          Verify.verify(status.getCode() == Status.Code.INTERNAL);
          Verify.verify(status.getDescription().contains("Crybaby"));
          // Cause is not transmitted over the wire..
          latch.countDown();
        }
      },
      directExecutor());

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 10
Source File: ClusterDeploymentTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private void undeploy(final JobId jobId, final String host) throws Exception {

    Futures.addCallback(client.undeploy(jobId, host), new FutureCallback<JobUndeployResponse>() {
          @Override
          public void onSuccess(final JobUndeployResponse result) {
            assertEquals(JobUndeployResponse.Status.OK, result.getStatus());
          }

          @Override
          public void onFailure(@NotNull final Throwable th) {
            fail("undeploy failed");
          }
        },
        MoreExecutors.directExecutor());
  }
 
Example 11
Source File: FailureRetryZKClient.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public OperationFuture<Stat> exists(final String path, final Watcher watcher) {
  final SettableOperationFuture<Stat> result = SettableOperationFuture.create(path, Threads.SAME_THREAD_EXECUTOR);
  Futures.addCallback(super.exists(path, watcher),
                      new OperationFutureCallback<Stat>(OperationType.EXISTS, System.currentTimeMillis(),
                                                        path, result, new Supplier<OperationFuture<Stat>>() {
                        @Override
                        public OperationFuture<Stat> get() {
                          return FailureRetryZKClient.super.exists(path, watcher);
                        }
                      }));
  return result;
}
 
Example 12
Source File: CompletableAsync.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
public static <T> void handle(ListenableFuture<T> future, HandlerConsumer<T> success, HandlerConsumer<Throwable> failure) {
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T v) {
            success.accept(v);
        }
        @Override
        public void onFailure(Throwable ex) {
            failure.accept(ex);
        }
    }, CompletableAsync.fxThread());          
}
 
Example 13
Source File: NamespaceZKClient.java    From twill with Apache License 2.0 5 votes vote down vote up
private <V> OperationFuture<V> relayFuture(final OperationFuture<V> from, final SettableOperationFuture<V> to) {
  Futures.addCallback(from, new FutureCallback<V>() {
    @Override
    public void onSuccess(V result) {
      to.set(result);
    }

    @Override
    public void onFailure(Throwable t) {
      to.setException(t);
    }
  });
  return to;
}
 
Example 14
Source File: BackpressureSemaphore.java    From flink-stream-processing-refarch with Apache License 2.0 5 votes vote down vote up
public void acquire(ListenableFuture<T> f) {
  try {
    semaphore.acquire();

    Futures.addCallback(f, this);
  } catch (InterruptedException e) {
    semaphore.release();
  }
}
 
Example 15
Source File: CGraphOpener.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public static void showGraphAndPerformCallBack(final IViewContainer container,
    final INaviView view, final CGraphWindow window, final Window parent,
    final FutureCallback<Boolean> callBack) {

  CWindowManager.instance().bringViewToFront(view);

  final ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors
      .newFixedThreadPool(10));

  final ListenableFuture<Boolean> loader = service.submit(generateViewLoader(view, container,
      window, parent));

  Futures.addCallback(loader, callBack);
}
 
Example 16
Source File: OneCameraImpl.java    From Camera2 with Apache License 2.0 4 votes vote down vote up
private void saveJpegPicture(byte[] jpegData, final PhotoCaptureParameters captureParams, CaptureSession session,
                             CaptureResult result)
{
    int heading = captureParams.heading;
    int width = 0;
    int height = 0;
    int rotation = 0;
    ExifInterface exif = null;
    try
    {
        exif = new ExifInterface();
        exif.readExif(jpegData);

        Integer w = exif.getTagIntValue(ExifInterface.TAG_PIXEL_X_DIMENSION);
        width = (w == null) ? width : w;
        Integer h = exif.getTagIntValue(ExifInterface.TAG_PIXEL_Y_DIMENSION);
        height = (h == null) ? height : h;

        // Get image rotation from EXIF.
        rotation = Exif.getOrientation(exif);

        // Set GPS heading direction based on sensor, if location is on.
        if (heading >= 0)
        {
            ExifTag directionRefTag = exif.buildTag(ExifInterface.TAG_GPS_IMG_DIRECTION_REF, ExifInterface
                    .GpsTrackRef.MAGNETIC_DIRECTION);
            ExifTag directionTag = exif.buildTag(ExifInterface.TAG_GPS_IMG_DIRECTION, new Rational(heading, 1));
            exif.setTag(directionRefTag);
            exif.setTag(directionTag);
        }
        new ExifUtil(exif).populateExif(Optional.<TaskImageContainer.TaskImage>absent(), Optional.of(
                (CaptureResultProxy) new AndroidCaptureResultProxy(result)), Optional.<Location>absent());
    } catch (IOException e)
    {
        Log.w(TAG, "Could not read exif from gcam jpeg", e);
        exif = null;
    }
    ListenableFuture<Optional<Uri>> futureUri = session.saveAndFinish(jpegData, width, height, rotation, exif);
    Futures.addCallback(futureUri, new FutureCallback<Optional<Uri>>()
    {
        @Override
        public void onSuccess(Optional<Uri> uriOptional)
        {
            captureParams.callback.onPictureSaved(uriOptional.orNull());
        }

        @Override
        public void onFailure(Throwable throwable)
        {
            captureParams.callback.onPictureSaved(null);
        }
    });
}
 
Example 17
Source File: FeeService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public void requestFees(@Nullable Runnable resultHandler, @Nullable FaultHandler faultHandler) {
    long now = Instant.now().getEpochSecond();
    // We all requests only each 2 minutes
    if (now - lastRequest > MIN_PAUSE_BETWEEN_REQUESTS_IN_MIN * 60) {
        lastRequest = now;
        FeeRequest feeRequest = new FeeRequest();
        SettableFuture<Tuple2<Map<String, Long>, Map<String, Long>>> future = feeRequest.getFees(feeProvider);
        Futures.addCallback(future, new FutureCallback<Tuple2<Map<String, Long>, Map<String, Long>>>() {
            @Override
            public void onSuccess(@Nullable Tuple2<Map<String, Long>, Map<String, Long>> result) {
                UserThread.execute(() -> {
                    checkNotNull(result, "Result must not be null at getFees");
                    timeStampMap = result.first;
                    epochInSecondAtLastRequest = timeStampMap.get("bitcoinFeesTs");
                    final Map<String, Long> map = result.second;
                    txFeePerByte = map.get("BTC");

                    if (txFeePerByte < minFeePerByte) {
                        log.warn("The delivered fee per byte is smaller than the min. default fee of 5 sat/byte");
                        txFeePerByte = minFeePerByte;
                    }

                    feeUpdateCounter.set(feeUpdateCounter.get() + 1);
                    log.info("BTC tx fee: txFeePerByte={}", txFeePerByte);
                    if (resultHandler != null)
                        resultHandler.run();
                });
            }

            @Override
            public void onFailure(@NotNull Throwable throwable) {
                log.warn("Could not load fees. feeProvider={}, error={}", feeProvider.toString(), throwable.toString());
                if (faultHandler != null)
                    UserThread.execute(() -> faultHandler.handleFault("Could not load fees", throwable));
            }
        });
    } else {
        log.debug("We got a requestFees called again before min pause of {} minutes has passed.", MIN_PAUSE_BETWEEN_REQUESTS_IN_MIN);
        UserThread.execute(() -> {
            if (resultHandler != null)
                resultHandler.run();
        });
    }
}
 
Example 18
Source File: GuavaConvertedFutureTestHelper.java    From future-converter with Apache License 2.0 4 votes vote down vote up
@Override
public void addCallbackTo(ListenableFuture<String> convertedFuture) {
    Futures.addCallback(convertedFuture, callback);
    convertedFuture.addListener(this::callbackCalled, MoreExecutors.directExecutor());
}
 
Example 19
Source File: MilvusGrpcClient.java    From milvus-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<InsertResponse> insertAsync(@Nonnull InsertParam insertParam) {

  if (!channelIsReadyOrIdle()) {
    logWarning("You are not connected to Milvus server");
    return Futures.immediateFuture(
        new InsertResponse(
            new Response(Response.Status.CLIENT_NOT_CONNECTED), new ArrayList<>()));
  }

  List<RowRecord> rowRecordList =
      buildRowRecordList(insertParam.getFloatVectors(), insertParam.getBinaryVectors());

  io.milvus.grpc.InsertParam request =
      io.milvus.grpc.InsertParam.newBuilder()
          .setCollectionName(insertParam.getCollectionName())
          .addAllRowRecordArray(rowRecordList)
          .addAllRowIdArray(insertParam.getVectorIds())
          .setPartitionTag(insertParam.getPartitionTag())
          .build();

  ListenableFuture<VectorIds> response;

  response = futureStub.insert(request);

  Futures.addCallback(
      response,
      new FutureCallback<VectorIds>() {
        @Override
        public void onSuccess(VectorIds result) {
          if (result.getStatus().getErrorCode() == ErrorCode.SUCCESS) {
            logInfo(
                "Inserted {} vectors to collection `{}` successfully!",
                result.getVectorIdArrayCount(),
                insertParam.getCollectionName());
          } else {
            logError("InsertAsync failed:\n{}", result.getStatus().toString());
          }
        }

        @Override
        public void onFailure(Throwable t) {
          logError("InsertAsync failed:\n{}", t.getMessage());
        }
      },
      MoreExecutors.directExecutor());

  Function<VectorIds, InsertResponse> transformFunc =
      vectorIds -> {
        if (vectorIds.getStatus().getErrorCode() == ErrorCode.SUCCESS) {
          return new InsertResponse(
              new Response(Response.Status.SUCCESS), vectorIds.getVectorIdArrayList());
        } else {
          return new InsertResponse(
              new Response(
                  Response.Status.valueOf(vectorIds.getStatus().getErrorCodeValue()),
                  vectorIds.getStatus().getReason()),
              new ArrayList<>());
        }
      };

  return Futures.transform(response, transformFunc::apply, MoreExecutors.directExecutor());
}
 
Example 20
Source File: SendMessageCommandProcessorV3.java    From hermes with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final CommandProcessorContext ctx) {
	SendMessageCommandV3 reqCmd = (SendMessageCommandV3) ctx.getCommand();
	String topic = reqCmd.getTopic();
	int partition = reqCmd.getPartition();

	logReqToCat(reqCmd);

	Lease lease = m_leaseContainer.acquireLease(topic, partition, m_config.getSessionId());

	if (m_metaService.findTopicByName(topic) != null) {
		if (lease != null) {
			if (log.isDebugEnabled()) {
				log.debug("Send message reqeust arrived(topic={}, partition={}, msgCount={})", topic, partition,
				      reqCmd.getMessageCount());
			}
			int bytes = calSize(reqCmd.getMessageRawDataBatches());

			if (!isRateLimitExceeded(topic, partition, reqCmd.getMessageCount(), bytes)) {
				writeAck(ctx, true);

				Map<Integer, MessageBatchWithRawData> rawBatches = reqCmd.getMessageRawDataBatches();

				bizLog(ctx, rawBatches, partition);

				final SendMessageResultCommand result = new SendMessageResultCommand(reqCmd.getMessageCount());
				result.correlate(reqCmd);

				FutureCallback<Map<Integer, SendMessageResult>> completionCallback = new AppendMessageCompletionCallback(
				      result, ctx, topic, partition);

				for (Map.Entry<Integer, MessageBatchWithRawData> entry : rawBatches.entrySet()) {
					MessageBatchWithRawData batch = entry.getValue();
					try {
						ListenableFuture<Map<Integer, SendMessageResult>> future = m_queueManager.appendMessageAsync(
						      topic, partition, entry.getKey() == 0 ? true : false, batch, m_systemClockService.now()
						            + reqCmd.getTimeout());

						if (future != null) {
							Futures.addCallback(future, completionCallback);
						}
					} catch (Exception e) {
						log.error("Failed to append messages async.", e);
					}
				}
			} else {
				reqCmd.release();
			}

		} else {
			if (log.isDebugEnabled()) {
				log.debug("No broker lease to handle client send message reqeust(topic={}, partition={})", topic,
				      partition);
			}
			writeAck(ctx, false);
			reqCmd.release();
		}
	} else {
		if (log.isDebugEnabled()) {
			log.debug("Topic {} not found", topic);
		}
		writeAck(ctx, false);
		reqCmd.release();
	}

}