com.google.common.util.concurrent.Futures Java Examples

The following examples show how to use com.google.common.util.concurrent.Futures. 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: BlazeAndroidRunConfigurationRunner.java    From intellij with Apache License 2.0 7 votes vote down vote up
private static String canDebug(
    DeviceFutures deviceFutures, AndroidFacet facet, String moduleName) {
  // If we are debugging on a device, then the app needs to be debuggable
  for (ListenableFuture<IDevice> future : deviceFutures.get()) {
    if (!future.isDone()) {
      // this is an emulator, and we assume that all emulators are debuggable
      continue;
    }
    IDevice device = Futures.getUnchecked(future);
    if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
      return AndroidBundle.message(
          "android.cannot.debug.noDebugPermissions", moduleName, device.getName());
    }
  }
  return null;
}
 
Example #2
Source File: MobileServicePush.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the client for push notification using device {@link Installation}
 *
 * @param installation device installation in Azure Notification Hub (https://msdn.microsoft.com/en-us/library/azure/mt621153.aspx)
 * @return Future with registration information
 */
public ListenableFuture<Void> register(Installation installation) {
    final SettableFuture<Void> resultFuture = SettableFuture.create();

    ListenableFuture<Void> registerInternalFuture = createOrUpdateInstallation(installation);

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

        @Override
        public void onSuccess(Void v) {
            resultFuture.set(v);
        }
    }, MoreExecutors.directExecutor());

    return resultFuture;
}
 
Example #3
Source File: TestExpressionCompiler.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testBinaryOperatorsDecimalBigint()
        throws Exception
{
    for (BigDecimal left : decimalLefts) {
        for (Long right : longRights) {
            assertExecute(generateExpression("%s = %s", left, right), BOOLEAN, left == null || right == null ? null : left.equals(new BigDecimal(right)));
            assertExecute(generateExpression("%s <> %s", left, right), BOOLEAN, left == null || right == null ? null : !left.equals(new BigDecimal(right)));
            assertExecute(generateExpression("%s > %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) > 0);
            assertExecute(generateExpression("%s < %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) < 0);
            assertExecute(generateExpression("%s >= %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) >= 0);
            assertExecute(generateExpression("%s <= %s", left, right), BOOLEAN, left == null || right == null ? null : left.compareTo(new BigDecimal(right)) <= 0);

            assertExecute(generateExpression("nullif(%s, %s)", left, right), BigDecimal.class.cast(nullIf(left, right)));

            assertExecute(generateExpression("%s is distinct from %s", left, right), BOOLEAN,
                    !Objects.equals(left, right == null ? null : new BigDecimal(right)));

            // arithmetic operators are already tested in TestDecimalOperators
        }
    }

    Futures.allAsList(futures).get();
}
 
Example #4
Source File: Peer.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <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>
 */
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
    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<>();
    // future will be invoked when the entire dependency tree has been walked and the results compiled.
    final ListenableFuture<Object> future = downloadDependenciesInternal(vDownloadTxDependencyDepth, 0, tx,
            new Object(), results);
    final SettableFuture<List<Transaction>> resultFuture = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object ignored) {
            resultFuture.set(results);
        }

        @Override
        public void onFailure(Throwable throwable) {
            resultFuture.setException(throwable);
        }
    });
    return resultFuture;
}
 
Example #5
Source File: BrokerMessageSender.java    From hermes with Apache License 2.0 6 votes vote down vote up
public Future<SendResult> submit(final ProducerMessage<?> msg) {
	SettableFuture<SendResult> future = SettableFuture.create();

	if (msg.getCallback() != null) {
		Futures.addCallback(future, new FutureCallback<SendResult>() {

			@Override
			public void onSuccess(SendResult result) {
				msg.getCallback().onSuccess(result);
			}

			@Override
			public void onFailure(Throwable t) {
				msg.getCallback().onFailure(t);
			}
		}, m_callbackExecutor);
	}

	offer(msg, future);

	return future;
}
 
Example #6
Source File: EntityConcurrencyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentAddTag() throws Exception {
    final int NUM_TASKS = Math.min(500 * Runtime.getRuntime().availableProcessors(), 1000);
    
    List<ListenableFuture<?>> futures = Lists.newArrayList();
    List<Integer> tags = Lists.newArrayList();
    
    for (int i = 0; i < NUM_TASKS; i++) {
        final int val = i;
        ListenableFuture<?> future = executor.submit(new Runnable() {
            @Override public void run() {
                entity.tags().addTag(val);
            }});
        futures.add(future);
        tags.add(val);
    }

    Futures.allAsList(futures).get();
    
    Asserts.assertEqualsIgnoringOrder(entity.tags().getTags(), tags);
}
 
Example #7
Source File: MobileServicePush.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the client for template notifications
 *
 * @param pnsHandle    PNS specific identifier
 * @param templateName The template name
 * @param template     The template body
 * @param callback     The operation callback
 * @deprecated use {@link #registerTemplate(String pnsHandle, String templateName, String template)} instead
 */
public void registerTemplate(String pnsHandle, String templateName, String template, final RegistrationCallback callback) {
    ListenableFuture<Void> registerFuture = registerTemplate(pnsHandle, templateName, template);

    Futures.addCallback(registerFuture, new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onRegister((Exception) exception);
            }
        }

        @Override
        public void onSuccess(Void v) {
            callback.onRegister(null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #8
Source File: MoreFutures.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static <V, R> ListenableFuture<R> transformAsync(ListenableFuture<V> future,
        Executor asyncExecutor, AsyncFunction<V, R> function) {
    boolean inRollupThread = Session.isInRollupThread();
    return Futures.transformAsync(future,
            new AsyncFunction<V, R>() {
                @Override
                public ListenableFuture<R> apply(V input) throws Exception {
                    boolean priorInRollupThread = Session.isInRollupThread();
                    Session.setInRollupThread(inRollupThread);
                    try {
                        return function.apply(input);
                    } finally {
                        Session.setInRollupThread(priorInRollupThread);
                    }
                }
            },
            // calls to Session.readAsync() inside of the function could block due to the
            // per-thread concurrent limit, so this needs to be executed in its own thread, not
            // in the cassandra driver thread that completes the last future which will block
            // the cassandra driver thread pool
            asyncExecutor);
}
 
Example #9
Source File: OutputS3.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    UploadPartRequest uploadPartRequest = new UploadPartRequest()
            .withBucketName(bucketName)
            .withKey(key)
            .withPartNumber(partNumber)
            .withPartSize(outputStream.size())
            .withUploadId(multipartUpload.getUploadId())
            .withInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
    UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
    etags.add(uploadPartResult.getPartETag());
    ListenableFuture<List<Object>> future = Futures.allAsList(pendingUploads);
    try {
        future.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new IOException(e);
    }
    client.completeMultipartUpload(
            new CompleteMultipartUploadRequest(
                    bucketName,
                    key,
                    multipartUpload.getUploadId(),
                    etags)
    );
    super.close();
}
 
Example #10
Source File: EntityLifecycleEnrichersTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testManuallySettingServiceStateIsNotOverwritten() throws Exception {
    List<ListenableFuture<?>> futures = Lists.newArrayList();
    for (int i = 0; i < 100; i++) {
        ListenableFuture<Void> future = executor.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                TestEntity entity = app.addChild(EntitySpec.create(TestEntity.class));
                entity.sensors().set(TestEntity.SERVICE_UP, true);
                entity.sensors().set(TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
                Thread.sleep(10);
                assertEquals(entity.sensors().get(TestEntity.SERVICE_UP), Boolean.TRUE);
                assertEquals(entity.sensors().get(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
                Entities.unmanage(entity);
                return null;
            }});
        futures.add(future);
    }
    Futures.allAsList(futures).get();
}
 
Example #11
Source File: ByteStreamUploader.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
ListenableFuture<Void> start() {
  ProgressiveBackoff progressiveBackoff = new ProgressiveBackoff(retrier::newBackoff);
  AtomicLong committedOffset = new AtomicLong(0);
  return Futures.transformAsync(
      retrier.executeAsync(
          () -> callAndQueryOnFailure(committedOffset, progressiveBackoff), progressiveBackoff),
      (result) -> {
        long committedSize = committedOffset.get();
        long expected = chunker.getSize();
        if (committedSize != expected) {
          String message =
              format(
                  "write incomplete: committed_size %d for %d total", committedSize, expected);
          return Futures.immediateFailedFuture(new IOException(message));
        }
        return Futures.immediateFuture(null);
      },
      MoreExecutors.directExecutor());
}
 
Example #12
Source File: PaymentChannelClientState.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
protected void watchCloseConfirmations() {
    // When we see the close transaction get enough confirmations, we can just delete the record
    // of this channel along with the refund tx from the wallet, because we're not going to need
    // any of that any more.
    final TransactionConfidence confidence = storedChannel.close.getConfidence();
    int numConfirms = Context.get().getEventHorizon();
    ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD);
    Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
        @Override
        public void onSuccess(TransactionConfidence result) {
            deleteChannelFromWallet();
        }

        @Override
        public void onFailure(Throwable t) {
            Throwables.propagate(t);
        }
    });
}
 
Example #13
Source File: VersionedSchedulerDriverService.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public void declineOffer(OfferID offerId, Filters filter) {
  whenRegistered(() -> {
    LOG.info("Declining offer {}", offerId.getValue());

    Futures.getUnchecked(mesosFuture).send(
        Call.newBuilder().setType(Call.Type.DECLINE)
            .setFrameworkId(getFrameworkId())
            .setDecline(
                Call.Decline.newBuilder()
                    .setFilters(filter)
                    .addOfferIds(offerId))
            .build()
    );
  });
}
 
Example #14
Source File: RetryingRequestDispatcherTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureOnTimeout() throws Exception {
  when(delegate.request(any(URI.class), anyString(), any(byte[].class),
      Matchers.<Map<String, List<String>>>any()))
      .thenReturn(Futures.<Response>immediateFailedFuture(new IOException()))
      .thenReturn(Futures.<Response>immediateFuture(null));

  when(clock.now()).thenReturn(new Instant(0)).thenReturn(new Instant(80000));

  final ListenableFuture<Response> future = dispatcher.request(
      new URI("http://example.com"), "GET", null, Collections.<String, List<String>>emptyMap());

  // Verify the delegate was only called once if it failed on the first try and the deadline
  // has passed before the second try was attempted.
  verify(delegate, times(1)).request(any(URI.class), anyString(), any(byte[].class),
      Matchers.<Map<String, List<String>>>any());
  exception.expect(ExecutionException.class);
  exception.expectCause(CoreMatchers.any(IOException.class));
  future.get();
}
 
Example #15
Source File: SchemaModuleTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void schemaModuleShouldApplyProtoEnumArgs() {
  Injector injector =
      Guice.createInjector(
          new SchemaModule() {

            @Mutation("mutationMethodWithArgs")
            ListenableFuture<GreetingsResponse> mutationMethod(
                GreetingsRequest request, @Arg("myLanguage") Greetings.Languages myLanguage) {
              return Futures.immediateFuture(
                  GreetingsResponse.newBuilder().setId(request.getId()).build());
            }
          });
  SchemaBundle schemaBundle = SchemaBundle.combine(injector.getInstance(KEY));
  assertThat(schemaBundle.mutationFields()).hasSize(1);

  List<GraphQLArgument> arguments = schemaBundle.mutationFields().get(0).getArguments();
  assertThat(arguments).hasSize(2);
  assertThat(
          arguments.stream()
              .map(argument -> argument.getName())
              .collect(ImmutableList.toImmutableList()))
      .containsExactly("input", "myLanguage");
}
 
Example #16
Source File: SwingExecutorService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected <T> Future<T> doInvoke(Callable<T> callable) {
   try {
      // always run after the current event finishes processing
      // this gives more natural behavior from the event thread
      SettableFuture<T> result = SettableFuture.create();
      SwingUtilities.invokeLater(() -> {
         if(result.isCancelled()) {
            return;
         }
         try {
            result.set(callable.call());
         }
         catch(Throwable t) {
         	logger.warn("Uncaught exception", t);
            result.setException(t);
         }
      });
      return result;
   }
   catch(Exception e) {
   	logger.warn("Uncaught exception", e);
      return Futures.immediateFailedFuture(e);
   }
}
 
Example #17
Source File: HealthCheckDirectiveHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<HealthCheckResponse> ping() {
   PlatformMessage msg = PlatformMessage.buildRequest(MessageBody.ping(), AlexaUtil.ADDRESS_BRIDGE, STATUS_SERVICE)
         .withCorrelationId(IrisUUID.randomUUID().toString())
         .create();

   ListenableFuture<PlatformMessage> future = platSvc.request(
      msg,
      (pm) -> Objects.equals(msg.getCorrelationId(), pm.getCorrelationId()), config.getHealthCheckTimeoutSecs()
   );

   return Futures.transform(future, (Function<PlatformMessage, HealthCheckResponse>) input -> {
      HealthCheckResponse response = new HealthCheckResponse();
      response.setHealthy(true);
      response.setDescription("The system is currently healthy");
      return response;
   }, MoreExecutors.directExecutor());
}
 
Example #18
Source File: BuildEventArtifactUploaderFactoryMapTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  noConversionUploaderFactory =
      (CommandEnvironment env) ->
          new BuildEventArtifactUploader() {
            @Override
            public ListenableFuture<PathConverter> upload(Map<Path, LocalFile> files) {
              return Futures.immediateFuture(PathConverter.NO_CONVERSION);
            }

            @Override
            public boolean mayBeSlow() {
              return false;
            }

            @Override
            public void shutdown() {
              // Intentionally left empty.
            }
          };
  uploaderFactories =
      new BuildEventArtifactUploaderFactoryMap.Builder()
          .add("a", BuildEventArtifactUploaderFactory.LOCAL_FILES_UPLOADER_FACTORY)
          .add("b", noConversionUploaderFactory)
          .build();
}
 
Example #19
Source File: IndexingServiceTest.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void indexItemAndContent_smallContentIsInlined() throws Exception {
  ListenableFuture<Operation> expected = Futures.immediateFuture(new Operation());
  when(batchingService.indexItem(any())).thenReturn(expected);
  Item item = new Item().setName(GOOD_ID);
  ByteArrayContent content = ByteArrayContent.fromString("text/plain", "Hello World.");

  ListenableFuture<Operation> result = indexingService.indexItemAndContent(
      item, content, null, ContentFormat.TEXT, RequestMode.ASYNCHRONOUS);

  verify(quotaServer).acquire(Operations.DEFAULT);
  verify(batchingService).indexItem(indexCaptor.capture());
  Items.Index updateRequest = indexCaptor.getValue();
  assertEquals(ITEMS_RESOURCE_PREFIX + GOOD_ID, updateRequest.getName());
  IndexItemRequest indexItemRequest = (IndexItemRequest) updateRequest.getJsonContent();
  assertEquals(RequestMode.ASYNCHRONOUS.name(), indexItemRequest.getMode());
  assertEquals(
      new ItemContent()
      .encodeInlineContent("Hello World.".getBytes(UTF_8))
      .setContentFormat("TEXT"),
      indexItemRequest.getItem().getContent());
  assertThat(result, sameInstance(expected));
}
 
Example #20
Source File: ShuffleManager.java    From tez with Apache License 2.0 6 votes vote down vote up
public void run() throws IOException {
  Preconditions.checkState(inputManager != null, "InputManager must be configured");

  if (maxTimeToWaitForReportMillis > 0) {
    reporterExecutor = Executors.newSingleThreadExecutor(
        new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("ShuffleRunner {" + srcNameTrimmed + "}")
            .build());
    Future reporterFuture = reporterExecutor.submit(new ReporterCallable());
  }

  ListenableFuture<Void> runShuffleFuture = schedulerExecutor.submit(schedulerCallable);
  Futures.addCallback(runShuffleFuture, new SchedulerFutureCallback(), GuavaShim.directExecutor());
  // Shutdown this executor once this task, and the callback complete.
  schedulerExecutor.shutdown();
}
 
Example #21
Source File: TopologyProgramming.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ListenableFuture<RpcResult<SubmitRemoveLspOutput>> submitRemoveLsp(final SubmitRemoveLspInput input) {
    Preconditions.checkArgument(input.getNode() != null);
    Preconditions.checkArgument(input.getName() != null);

    final SubmitRemoveLspOutputBuilder b = new SubmitRemoveLspOutputBuilder();
    b.setResult(AbstractInstructionExecutor.schedule(this.scheduler, new AbstractInstructionExecutor(input) {
        @Override
        protected ListenableFuture<OperationResult> invokeOperation() {
            return TopologyProgramming.this.manager.removeLsp(input);
        }
    }));

    final RpcResult<SubmitRemoveLspOutput> res = SuccessfulRpcResult.create(b.build());
    return Futures.immediateFuture(res);
}
 
Example #22
Source File: ReplicatorService.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Void> getDependedOnModules() {
  SettableFuture<Void> doneFuture = SettableFuture.create();

  List<ListenableFuture<C5Module>> moduleFutures = new ArrayList<>();
  moduleFutures.add(moduleInformationProvider.getModule(ModuleType.Log));
  moduleFutures.add(moduleInformationProvider.getModule(ModuleType.Discovery));

  ListenableFuture<List<C5Module>> compositeModulesFuture = Futures.allAsList(moduleFutures);

  LOG.warn("ReplicatorService now waiting for module dependency on Log & Discovery");

  C5Futures.addCallback(compositeModulesFuture,
      (List<C5Module> modules) -> {
        this.logModule = (LogModule) modules.get(0);
        this.discoveryModule = (DiscoveryModule) modules.get(1);

        doneFuture.set(null);
      },
      this::failModule, fiber);

  return doneFuture;
}
 
Example #23
Source File: HybridLocalStrategy.java    From buck with Apache License 2.0 5 votes vote down vote up
public void cancel(Throwable reason) {
  synchronized (this) {
    if (future.isDone()) {
      return;
    }
    LOG.info("Canceling job building: %s", rule.getFullyQualifiedName());
    Optional<BuildResult> cancelledResult =
        Optional.of(strategyContext.createCancelledResult(reason));
    // TODO(cjhopman): We should probably have a more forceful cancellation that succeeds as
    // long as the delegate can ensure no future side effects will happen.

    if (this.delegateResult != null) {
      cancelDelegateLocked(reason);
    }

    if (this.delegateResult == null) {
      future.set(cancelledResult);
    } else {
      // We're unable to cancel the delegate, so delay the cancelled result until the delegate
      // finishes.
      future.setFuture(
          Futures.transform(
              this.delegateResult.getBuildResult(),
              ignored -> cancelledResult,
              MoreExecutors.directExecutor()));
    }
  }
}
 
Example #24
Source File: ByteStreamBuildEventArtifactUploaderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void remoteFileShouldNotBeUploaded_findMissingDigests() throws Exception {
  // Test that findMissingDigests is called to check which files exist remotely
  // and that those are not uploaded.

  // arrange
  Path remoteFile = fs.getPath("/remote-file");
  FileSystemUtils.writeContent(remoteFile, StandardCharsets.UTF_8, "hello world");
  Digest remoteDigest = DIGEST_UTIL.compute(remoteFile);
  Path localFile = fs.getPath("/local-file");
  FileSystemUtils.writeContent(localFile, StandardCharsets.UTF_8, "foo bar");
  Digest localDigest = DIGEST_UTIL.compute(localFile);

  StaticMissingDigestsFinder digestQuerier =
      Mockito.spy(new StaticMissingDigestsFinder(ImmutableSet.of(remoteDigest)));
  ByteStreamUploader uploader = Mockito.mock(ByteStreamUploader.class);
  when(uploader.uploadBlobAsync(any(), any(), anyBoolean()))
      .thenReturn(Futures.immediateFuture(null));
  ByteStreamBuildEventArtifactUploader artifactUploader =
      newArtifactUploader(uploader, digestQuerier);

  // act
  Map<Path, LocalFile> files =
      ImmutableMap.of(
          remoteFile,
          new LocalFile(remoteFile, LocalFileType.OUTPUT),
          localFile,
          new LocalFile(localFile, LocalFileType.OUTPUT));
  PathConverter pathConverter = artifactUploader.upload(files).get();

  // assert
  verify(digestQuerier).findMissingDigests(any());
  verify(uploader)
      .uploadBlobAsync(eq(HashCode.fromString(localDigest.getHash())), any(), anyBoolean());
  assertThat(pathConverter.apply(remoteFile)).contains(remoteDigest.getHash());
  assertThat(pathConverter.apply(localFile)).contains(localDigest.getHash());
}
 
Example #25
Source File: WebRTCWrapper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@Nonnull
private ListenableFuture<PeerConnection> getPeerConnectionFuture() {
    final PeerConnection peerConnection = this.peerConnection;
    if (peerConnection == null) {
        return Futures.immediateFailedFuture(new IllegalStateException("initialize PeerConnection first"));
    } else {
        return Futures.immediateFuture(peerConnection);
    }
}
 
Example #26
Source File: TestExpressionCompiler.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryOperatorsDecimalDouble()
        throws Exception
{
    for (BigDecimal left : decimalLefts) {
        for (Double right : doubleRights) {
            assertExecute(generateExpression("%s = %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() == right);
            assertExecute(generateExpression("%s <> %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() != right);
            assertExecute(generateExpression("%s > %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() > right);
            assertExecute(generateExpression("%s < %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() < right);
            assertExecute(generateExpression("%s >= %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() >= right);
            assertExecute(generateExpression("%s <= %s", left, right), BOOLEAN, left == null || right == null ? null : left.doubleValue() <= right);

            assertExecute(generateExpression("nullif(%s, %s)", left, right), BigDecimal.class.cast(nullIf(left, right)));

            assertExecute(generateExpression("%s is distinct from %s", left, right), BOOLEAN, !Objects.equals(left == null ? null : left.doubleValue(), right));

            assertExecute(generateExpression("%s + %s", left, right), DOUBLE, left == null || right == null ? null : left.doubleValue() + right);
            assertExecute(generateExpression("%s - %s", left, right), DOUBLE, left == null || right == null ? null : left.doubleValue() - right);
            assertExecute(generateExpression("%s * %s", left, right), DOUBLE, left == null || right == null ? null : left.doubleValue() * right);
            assertExecute(generateExpression("%s / %s", left, right), DOUBLE, left == null || right == null ? null : left.doubleValue() / right);
            assertExecute(generateExpression("%s %% %s", left, right), DOUBLE, left == null || right == null ? null : left.doubleValue() % right);
        }
    }

    Futures.allAsList(futures).get();
}
 
Example #27
Source File: PublishPollServiceImplTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_poll_shared_publishes() throws NoMessageIdAvailableException {
    final OrderedTopicHandler orderedTopicHandler = mock(OrderedTopicHandler.class);
    final byte flags = SubscriptionFlags.getDefaultFlags(true, false, false);
    when(sharedSubscriptionService.getSharedSubscriber(anyString())).thenReturn(ImmutableSet.of(
            new SubscriberWithQoS("client1", 2, flags, 1),
            new SubscriberWithQoS("client2", 2, flags, 2)));
    when(channelPersistence.get("client1")).thenReturn(channel);
    when(channelPersistence.get("client2")).thenReturn(null);

    when(clientQueuePersistence.readShared(eq("group/topic"), anyInt(), anyLong())).thenReturn(Futures.immediateFuture(
            ImmutableList.of(createPublish(1), createPublish(1), TestMessageUtil.createMqtt3Publish(QoS.AT_MOST_ONCE))));

    when(messageIDPool.takeNextId()).thenReturn(2).thenReturn(3);
    when(channel.isActive()).thenReturn(true);
    final AtomicInteger inFlightCount = new AtomicInteger(0);
    when(channel.attr(ChannelAttributes.IN_FLIGHT_MESSAGES)).thenReturn(new TestChannelAttribute<>(inFlightCount));
    when(channel.attr(ChannelAttributes.IN_FLIGHT_MESSAGES_SENT)).thenReturn(new TestChannelAttribute<>(true));

    when(pipeline.get(OrderedTopicHandler.class)).thenReturn(orderedTopicHandler);
    when(orderedTopicHandler.unacknowledgedMessages()).thenReturn(new HashSet<>());


    publishPollService.pollSharedPublishes("group/topic");

    final ArgumentCaptor<PUBLISH> captor = ArgumentCaptor.forClass(PUBLISH.class);
    verify(pipeline, times(3)).fireUserEventTriggered(captor.capture());
    verify(messageIDPool, times(2)).takeNextId();

    final List<PUBLISH> values = captor.getAllValues();
    assertEquals(2, values.get(0).getPacketIdentifier());
    assertEquals(QoS.AT_LEAST_ONCE, values.get(0).getQoS());
    assertEquals(1, values.get(0).getSubscriptionIdentifiers().get(0));

    assertEquals(3, values.get(1).getPacketIdentifier());
    assertEquals(QoS.AT_LEAST_ONCE, values.get(1).getQoS());
    assertEquals(1, values.get(1).getSubscriptionIdentifiers().get(0));
    assertEquals(3, inFlightCount.get());
}
 
Example #28
Source File: InMemoryCacheClient.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<ImmutableSet<Digest>> findMissingDigests(Iterable<Digest> digests) {
  ImmutableSet.Builder<Digest> missingBuilder = ImmutableSet.builder();
  for (Digest digest : digests) {
    if (!cas.containsKey(digest)) {
      missingBuilder.add(digest);
    }
  }
  return Futures.immediateFuture(missingBuilder.build());
}
 
Example #29
Source File: FamilyReadImplTest.java    From simple-bigtable with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteAsync() throws Exception {
  verifyReadRequest(familyRead.readRequest());
  when(bigtableMock.getMockedDataClient().readRowsAsync(any()))
          .thenReturn(Futures.immediateFuture(Collections.emptyList()));

  familyRead.executeAsync();

  verifyReadRequest(familyRead.readRequest()); // make sure execute did not change the read request
  verify(bigtableMock.getMockedDataClient()).readRowsAsync(familyRead.readRequest().build());
  verifyNoMoreInteractions(bigtableMock.getMockedDataClient());
}
 
Example #30
Source File: FutureMatchersTest.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptional() {
  final RuntimeException ex = new RuntimeException("oops");

  final Future<String> cf = Futures.immediateFailedFuture(ex);

  assertThat(cf, futureCompletedWithException());
  assertThat(cf, futureCompletedWithExceptionThat(is(sameInstance(ex))));
  assertThat(cf, futureCompletedWithExceptionThat(isA(RuntimeException.class)));
  assertThat(cf, futureWillCompleteWithException());
  assertThat(cf, futureWillCompleteWithExceptionThat(is(sameInstance(ex))));
  assertThat(cf, futureWillCompleteWithExceptionThat(isA(RuntimeException.class)));
}