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

The following examples show how to use com.google.common.util.concurrent.Futures#immediateFuture() . 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: CassandraAbstractModelDao.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
protected ListenableFuture<D> findOneByStatementAsync(Statement statement) {
    if (statement != null) {
        statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
        ResultSetFuture resultSetFuture = getSession().executeAsync(statement);
        return Futures.transform(resultSetFuture, new Function<ResultSet, D>() {
            @Nullable
            @Override
            public D apply(@Nullable ResultSet resultSet) {
                Result<E> result = getMapper().map(resultSet);
                if (result != null) {
                    E entity = result.one();
                    return DaoUtil.getData(entity);
                } else {
                    return null;
                }
            }
        });
    }
    return Futures.immediateFuture(null);
}
 
Example 2
Source File: ClusterManager.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<V> get(K key) throws Exception {
    V value = cache.get(key);
    if (value != null) {
        return Futures.immediateFuture(value);
    }
    ListenableFuture<V> future = loader.load(key);
    // FIXME there's a race condition if invalidation is received at this point
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override
        public void onSuccess(V v) {
            cache.put(key, v);
        }
        @Override
        public void onFailure(Throwable t) {}
        // ok to use direct executor since the cache is just a simple ConcurrentHashMap
    }, MoreExecutors.directExecutor());
    return future;
}
 
Example 3
Source File: TaskExecutorImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private <T, E extends Exception> ListenableFuture<T> submitWrappedTask(TaskLoggingWrapper<T, E> task) throws E
{
    checkState(task);
    if (isTaskExecutorThread())
    {
        if (LOGGER.isTraceEnabled())
        {
            LOGGER.trace("Running {} immediately", task);
        }
        T result = task.execute();
        return Futures.immediateFuture(result);
    }
    else
    {
        if (LOGGER.isTraceEnabled())
        {
            LOGGER.trace("Submitting {} to executor {}", task, _name);
        }

        return _executor.submit(new CallableWrapper<>(task));
    }
}
 
Example 4
Source File: AbstractLegacyAccessControlProvider.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@StateTransition(currentState = {State.UNINITIALIZED, State.QUIESCED, State.ERRORED}, desiredState = State.ACTIVE)
@SuppressWarnings("unused")
private ListenableFuture<Void> activate()
{

    final boolean isManagementMode = getModel().getAncestor(SystemConfig.class, this).isManagementMode();
    try
    {
        recreateAccessController();
        setState(isManagementMode ? State.QUIESCED : State.ACTIVE);
    }
    catch (RuntimeException e)
    {
        setState(State.ERRORED);
        if (isManagementMode)
        {
            LOGGER.warn("Failed to activate ACL provider: " + getName(), e);
        }
        else
        {
            throw e;
        }
    }
    return Futures.immediateFuture(null);
}
 
Example 5
Source File: TestTaskExecutor.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<?> processFor(Duration duration)
{
    started.set(true);
    ticker.increment(quantaTimeMillis, MILLISECONDS);
    globalPhaser.arriveAndAwaitAdvance();
    int phase = beginQuantaPhaser.arriveAndAwaitAdvance();
    firstPhase.compareAndSet(-1, phase - 1);
    lastPhase.set(phase);
    endQuantaPhaser.arriveAndAwaitAdvance();
    if (completedPhases.incrementAndGet() >= requiredPhases) {
        endQuantaPhaser.arriveAndDeregister();
        beginQuantaPhaser.arriveAndDeregister();
        globalPhaser.arriveAndDeregister();
        completed.set(null);
    }

    return Futures.immediateFuture(null);
}
 
Example 6
Source File: BlazeRuntime.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a logger that crashes as soon as it's written to, since tests should not cause events
 * that would be logged.
 */
@VisibleForTesting
public static Future<Logger> getTestCrashLogger() {
  Logger crashLogger = Logger.getAnonymousLogger();
  crashLogger.addHandler(
      new Handler() {
        @Override
        public void publish(LogRecord record) {
          System.err.println("Remote logging disabled for testing, forcing abrupt shutdown.");
          System.err.printf(
              "%s#%s: %s\n",
              record.getSourceClassName(), record.getSourceMethodName(), record.getMessage());

          Throwable e = record.getThrown();
          if (e != null) {
            e.printStackTrace();
          }

          Runtime.getRuntime().halt(ExitCode.BLAZE_INTERNAL_ERROR.getNumericExitCode());
        }

        @Override
        public void flush() {
          throw new IllegalStateException();
        }

        @Override
        public void close() {
          throw new IllegalStateException();
        }
      });
  return Futures.immediateFuture(crashLogger);
}
 
Example 7
Source File: AsyncUpdateMovieSource.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Update
public ListenableFuture<Movie> updateAllMovies(@Set("title") String title,
                                               @Set("category") String category,
                                               @Key("uuid") String uuid) {
    Movie movie = movies.get(uuid);
    if (movie != null) {
        movie.setTitle(title);
        movie.setCategory(category);
        return Futures.immediateFuture(movie);
    } else {
        return null;
    }
}
 
Example 8
Source File: JpaAttributeDao.java    From Groza with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Optional<AttributeKvEntry>> find(EntityId entityId, String attributeType, String attributeKey) {
    AttributeKvCompositeKey compositeKey =
            getAttributeKvCompositeKey(entityId, attributeType, attributeKey);
    return Futures.immediateFuture(
            Optional.ofNullable(DaoUtil.getData(attributeKvRepository.findById(compositeKey).get())));
}
 
Example 9
Source File: KeyVaultKeyResolver.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<IKey> resolveKeyAsync(String kid) {

    if (KeyIdentifier.isKeyIdentifier(kid)) {
        return resolveKeyFromKeyAsync(kid);
    } else if (SecretIdentifier.isSecretIdentifier(kid)) {
        return resolveKeyFromSecretAsync(kid);
    }

    return Futures.immediateFuture(null);
}
 
Example 10
Source File: GrpcCacheClient.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> downloadBlob(Digest digest, OutputStream out) {
  if (digest.getSizeBytes() == 0) {
    return Futures.immediateFuture(null);
  }

  @Nullable Supplier<HashCode> hashSupplier = null;
  if (options.remoteVerifyDownloads) {
    HashingOutputStream hashOut = digestUtil.newHashingOutputStream(out);
    hashSupplier = hashOut::hash;
    out = hashOut;
  }

  return downloadBlob(digest, out, hashSupplier);
}
 
Example 11
Source File: ExchangeClient.java    From presto with Apache License 2.0 5 votes vote down vote up
public synchronized ListenableFuture<?> isBlocked()
{
    if (isClosed() || isFailed() || pageBuffer.peek() != null) {
        return Futures.immediateFuture(true);
    }
    SettableFuture<?> future = SettableFuture.create();
    blockedCallers.add(future);
    return future;
}
 
Example 12
Source File: GenericPartitioningSpiller.java    From presto with Apache License 2.0 5 votes vote down vote up
private synchronized ListenableFuture<?> flush(int partition)
{
    PageBuilder pageBuilder = pageBuilders.get(partition);
    if (pageBuilder.isEmpty()) {
        return Futures.immediateFuture(null);
    }
    Page page = pageBuilder.build();
    pageBuilder.reset();
    return getSpiller(partition).spill(page);
}
 
Example 13
Source File: AbstractConfiguredObject.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
protected final ListenableFuture<Void> deleteChildren()
{
    // If this object manages its own child-storage then don't propagate the delete.  The rationale
    // is that deleting the object will delete the storage that contains the children.  Telling each
    // child and their children to delete themselves would generate unnecessary 'delete' work in the
    // child-storage (which also might fail).
    if (managesChildStorage())
    {
        return Futures.immediateFuture(null);
    }

    final List<ListenableFuture<Void>> childDeleteFutures = new ArrayList<>();

    applyToChildren(child -> {

        final ListenableFuture<Void> childDeleteFuture;
        if (child instanceof AbstractConfiguredObject<?>)
        {
             childDeleteFuture = ((AbstractConfiguredObject<?>) child).deleteNoChecks();
        }
        else if (child instanceof AbstractConfiguredObjectProxy)
        {
            childDeleteFuture = ((AbstractConfiguredObjectProxy) child).deleteNoChecks();
        }
        else
        {
            childDeleteFuture = Futures.immediateFuture(null);
        }

        addFutureCallback(childDeleteFuture, new FutureCallback<Void>()
        {
            @Override
            public void onSuccess(final Void result)
            {
            }

            @Override
            public void onFailure(final Throwable t)
            {
                LOGGER.error("Exception occurred while deleting {} : {}",
                             child.getClass().getSimpleName(), child.getName(), t);
            }
        }, getTaskExecutor());
        childDeleteFutures.add(childDeleteFuture);
    });

    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(childDeleteFutures);

    return Futures.transform(combinedFuture, input -> null, getTaskExecutor());
}
 
Example 14
Source File: AbstractPort.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@StateTransition( currentState = State.UNINITIALIZED, desiredState = State.QUIESCED)
private ListenableFuture<Void> startQuiesced()
{
    setState(State.QUIESCED);
    return Futures.immediateFuture(null);
}
 
Example 15
Source File: ByteStreamBuildEventArtifactUploaderTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<ImmutableSet<Digest>> findMissingDigests(Iterable<Digest> digests) {
  return Futures.immediateFuture(ImmutableSet.copyOf(digests));
}
 
Example 16
Source File: AbstractStandardVirtualHostNode.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Override
protected ListenableFuture<Void> activate()
{
    if (LOGGER.isDebugEnabled())
    {
        LOGGER.debug("Activating virtualhost node " + this);
    }

    getConfigurationStore().init(this);


    getConfigurationStore().upgradeStoreStructure();

    getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.CREATED());

    writeLocationEventLog();

    getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.RECOVERY_START());

    VirtualHostStoreUpgraderAndRecoverer upgrader = new VirtualHostStoreUpgraderAndRecoverer(this);
    ConfiguredObjectRecord[] initialRecords  = null;
    try
    {
        initialRecords = getInitialRecords();
    }
    catch (IOException e)
    {
        throw new IllegalConfigurationException("Could not process initial configuration", e);
    }

    final boolean isNew = upgrader.upgradeAndRecover(getConfigurationStore(), initialRecords);
    if(initialRecords.length > 0)
    {
        setAttributes(Collections.<String, Object>singletonMap(VIRTUALHOST_INITIAL_CONFIGURATION, "{}"));
    }

    getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.RECOVERY_COMPLETE());

    QueueManagingVirtualHost<?>  host = getVirtualHost();

    if (host != null)
    {
        final QueueManagingVirtualHost<?> recoveredHost = host;
        final ListenableFuture<Void> openFuture;
        recoveredHost.setFirstOpening(isNew && initialRecords.length == 0);
        openFuture = Subject.doAs(getSubjectWithAddedSystemRights(),
                                  new PrivilegedAction<ListenableFuture<Void>>()
                                  {
                                      @Override
                                      public ListenableFuture<Void> run()
                                      {
                                          return recoveredHost.openAsync();

                                      }
                                  });
        return openFuture;
    }
    else
    {
        return Futures.immediateFuture(null);
    }
}
 
Example 17
Source File: NestedSetStore.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<Void> put(ByteString fingerprint, byte[] serializedBytes) {
  fingerprintToContents.put(fingerprint, serializedBytes);
  return Futures.immediateFuture(null);
}
 
Example 18
Source File: MockPrefetchService.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<?> prefetchProjectFiles(
    Project project, ProjectViewSet projectViewSet, @Nullable BlazeProjectData blazeProjectData) {
  return Futures.immediateFuture(null);
}
 
Example 19
Source File: FitInvocationHandlerTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<String> runListenableFuture(String arg) {
    executionCounter++;
    return Futures.immediateFuture(arg);
}
 
Example 20
Source File: ClientDeviceServiceImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
/**
   *
   * Send a hub registration request.  This method sets up a Timer task that is scheduled at
   * {@code pollingIntervalInMS} and runs for {@code maxRetries} attempts before giving up and
   * returning a future set to false.
   *
   * If any errors, except a "Hub not found" error, will result in setting an exception on the
   * future.  Since the "Hub not found" error could be caused by the customer not plugging the hub
   * in yet, or is waiting for the hub to finish it's synchronization with the Hub Bridge, this
   * will continue to retry.
   *
   * @param hubID Clients HubID
   * @param maxRetries Number of attempts before giving up
   * @param timeoutPerRequestInMillis Time to wait for each individual request to come in
   * @param pollingIntervalInMS Time in between requests
   * @param useAdHocHandler If you want to use a registered handler for the HubAddedEvent or not.
   *
   * @return
   */
  public ListenableFuture<Boolean> registerHub(String hubID, int maxRetries, long timeoutPerRequestInMillis, long pollingIntervalInMS, boolean useAdHocHandler) {
  	hubRegisterTaskTimer = new Timer();
  	completedSuccessfully = SettableFuture.create();
  	retryNumber = 0;

  	if (maxRetries < 1) {
  		logger.trace("Max retries was set to: {}, require at least 1.", maxRetries);
  		return(Futures.immediateFuture(false));
  	}

  	if (pollingIntervalInMS < 500) {
  		logger.trace("Setting polling interval to at least 500 ms.  Was requested at: {}", pollingIntervalInMS);
  		pollingIntervalInMS = 500;
  	}

hubRegisterTaskTimer.schedule(new RegisterHubRequestTask(hubID, timeoutPerRequestInMillis, maxRetries, useAdHocHandler), 0, pollingIntervalInMS);
return(completedSuccessfully);
  }