Example usage for com.google.common.util.concurrent Futures immediateFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFuture

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures immediateFuture.

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) 

Source Link

Document

Creates a ListenableFuture which has its value set immediately upon construction.

Usage

From source file:com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService.java

@Override
public <T> Future<Map<T, Long>> incrementAll(Collection<T> keys, long delta, Long initialValue) {
    return Futures.immediateFuture(memcacheService.incrementAll(keys, delta, initialValue));
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeMediaItemSPI.java

@Override
public Future<MediaItem> getMediaItem(UserId userId, String appId, String albumId, String mediaItemId,
        Set<String> fields, SecurityToken token) throws ProtocolException {
    MediaItem mediaItem = null;/*  w  ww.  ja  v a  2 s .c  om*/

    // create query
    final WebsockQuery query = new WebsockQuery(EQueryType.PROCEDURE_CALL);
    query.setPayload(ShindigNativeQueries.GET_MEDIA_ITEM_QUERY);

    // set parameters for method
    query.setParameter(ShindigNativeQueries.USER_ID, userId.getUserId(token));
    query.setParameter(ShindigNativeQueries.APP_ID, appId);
    query.setParameter(ShindigNativeQueries.ALBUM_ID, albumId);
    query.setParameter(ShindigNativeQueries.MEDIA_ITEM_ID, mediaItemId);

    if (fields != null) {
        final List<String> fieldList = new ArrayList<String>(fields);
        query.setParameter(ShindigNativeQueries.FIELD_LIST, fieldList);
    }

    // execute
    final IQueryCallback result = this.fQueryHandler.sendQuery(query);
    SingleResult sResult = null;

    try {
        sResult = (SingleResult) result.get();

        // TODO: proper not found exception
        if (sResult == null) {
            return null;
        }
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not retrieve result",
                e);
    }

    @SuppressWarnings("unchecked")
    final Map<String, Object> map = (Map<String, Object>) sResult.getResults();
    mediaItem = new MediaItemDTO(map);

    return Futures.immediateFuture(mediaItem);
}

From source file:com.facebook.buck.parser.ConvertingPipeline.java

private ListenableFuture<T> dispatchComputeNode(Cell cell, BuildTarget buildTarget, F from)
        throws BuildTargetException {
    // TODO(csarbora): would be nice to have the first half of this function pulled up into base
    if (shuttingDown()) {
        return Futures.immediateCancelledFuture();
    }//from  ww  w.  ja  v  a  2s.c om

    if (!isValid(from)) {
        throw new NoSuchBuildTargetException(buildTarget);
    }

    Path pathToCheck = buildTarget.getBasePath();
    if (cell.getFilesystem().isIgnored(pathToCheck)) {
        throw new HumanReadableException(
                "Content of '%s' cannot be built because" + " it is defined in an ignored directory.",
                pathToCheck);
    }

    return Futures.immediateFuture(computeNode(cell, buildTarget, from));
}

From source file:org.opendaylight.netvirt.elan.statisitcs.ElanStatisticsImpl.java

@Override
public Future<RpcResult<GetElanInterfaceStatisticsOutput>> getElanInterfaceStatistics(
        GetElanInterfaceStatisticsInput input) {
    String interfaceName = input.getInterfaceName();
    LOG.debug("getElanInterfaceStatistics is called for elan interface {}", interfaceName);
    RpcResultBuilder<GetElanInterfaceStatisticsOutput> rpcResultBuilder = null;
    if (interfaceName == null) {
        rpcResultBuilder = RpcResultBuilder.failed();
        return getFutureWithAppErrorMessage(rpcResultBuilder, "Interface name is not provided");
    }//from   ww  w  .j  a  v a 2s  . com
    ElanInterface elanInterface = ElanUtils.getElanInterfaceByElanInterfaceName(dataBroker, interfaceName);
    if (elanInterface == null) {
        rpcResultBuilder = RpcResultBuilder.failed();
        return getFutureWithAppErrorMessage(rpcResultBuilder,
                String.format("Interface %s is not a ELAN interface", interfaceName));
    }
    String elanInstanceName = elanInterface.getElanInstanceName();
    ElanInstance elanInfo = ElanUtils.getElanInstanceByName(dataBroker, elanInstanceName);
    long elanTag = elanInfo.getElanTag();
    InterfaceInfo interfaceInfo = interfaceManager.getInterfaceInfo(interfaceName);
    ServicesInfo serviceInfo = ElanUtils.getServiceInfo(elanInstanceName, elanTag, interfaceName);
    //FIXME [ELANBE] Get this API Later
    short tableId = 0;
    //        try {
    //
    //            //tableId = interfaceManager.getTableIdForService(interfaceName, serviceInfo);
    //        } catch (InterfaceNotFoundException | InterfaceServiceNotFoundException e) {
    //            rpcResultBuilder = RpcResultBuilder.failed();
    //            return getFutureWithAppErrorMessage(rpcResultBuilder,
    //                String.format("Interface %s or Service %s doesn't exist", interfaceName, serviceInfo));
    //        }
    if (!interfaceInfo.isOperational()) {
        LOG.debug("interface {} is down and returning with no statistics", interfaceName);
        rpcResultBuilder = RpcResultBuilder.success();
        return Futures.immediateFuture(rpcResultBuilder
                .withResult(new GetElanInterfaceStatisticsOutputBuilder().setStatResult(
                        new StatResultBuilder().setStatResultCode(ResultCode.NotFound).setByteRxCount(0L)
                                .setByteTxCount(0L).setPacketRxCount(0L).setPacketTxCount(0L).build())
                        .build())
                .build());
    }
    rpcResultBuilder = RpcResultBuilder.success();
    return Futures.immediateFuture(rpcResultBuilder
            .withResult(queryforElanInterfaceStatistics(tableId, elanInstanceName, interfaceInfo)).build());
}

From source file:com.google.gapid.models.CommandStream.java

public ListenableFuture<Node> load(Node node) {
    return node.load(shell, () -> Futures
            .transformAsync(client.get(Paths.toAny(node.getPath(Path.CommandTreeNode.newBuilder()))), v1 -> {
                Service.CommandTreeNode data = v1.getCommandTreeNode();
                if (data.getGroup().isEmpty() && data.hasCommands()) {
                    return Futures.transform(loadCommand(lastCommand(data.getCommands())),
                            cmd -> new NodeData(data, cmd));
                }/* w  w  w .  java  2  s.co m*/
                return Futures.immediateFuture(new NodeData(data, null));
            }));
}

From source file:org.apache.shindig.social.websockbackend.spi.WsNativeGroupSPI.java

@Override
public Future<RestfulCollection<Group>> getGroups(UserId userId, CollectionOptions options, Set<String> fields,
        SecurityToken token) throws ProtocolException {
    final List<Group> groupList = new ArrayList<Group>();

    final String sortField = options.getSortBy();
    if (sortField == null) {
        options.setSortBy(WsNativeGroupSPI.TITLE_FIELD);
    }/* w w w .  j ava2s . c o m*/

    // create query
    final WebsockQuery query = new WebsockQuery(EQueryType.PROCEDURE_CALL);
    query.setPayload(ShindigNativeQueries.GET_GROUPS_QUERY);

    // set options
    CollOptsConverter.convert(options, query);

    // set parameters for method
    query.setParameter(ShindigNativeQueries.USER_ID, userId.getUserId(token));

    if (fields != null) {
        final List<String> fieldList = new ArrayList<String>(fields);
        query.setParameter(ShindigNativeQueries.FIELD_LIST, fieldList);
    }

    final IQueryCallback result = this.fQueryHandler.sendQuery(query);

    ListResult resultList = null;
    try {
        resultList = (ListResult) result.get();
    } catch (final Exception e) {
        e.printStackTrace();
        this.fLogger.log(Level.SEVERE, "server error", e);
        throw new ProtocolException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "could not retrieve results",
                e);
    }

    @SuppressWarnings("unchecked")
    final List<Map<String, Object>> mapList = (List<Map<String, Object>>) resultList.getResults();

    // convert the items requested
    GroupDTO dto = null;

    if (mapList != null) {
        for (final Map<String, Object> groupMap : mapList) {
            dto = new GroupDTO(groupMap);
            groupList.add(dto);
        }
    }

    final RestfulCollection<Group> groups = new RestfulCollection<Group>(groupList);
    groups.setItemsPerPage(resultList.getMax());
    groups.setStartIndex(resultList.getFirst());
    groups.setTotalResults(resultList.getTotal());
    return Futures.immediateFuture(groups);
}

From source file:com.orangerhymelabs.helenus.cassandra.AbstractCassandraRepository.java

public ListenableFuture<Boolean> delete(Identifier id) {
    ListenableFuture<ResultSet> future = submitDelete(id);
    return Futures.transformAsync(future, new AsyncFunction<ResultSet, Boolean>() {
        @Override//from   ww w  .  j av  a2  s .c om
        public ListenableFuture<Boolean> apply(ResultSet result) {
            if (!result.wasApplied()) {
                return Futures.immediateFailedFuture(new ItemNotFoundException(id.toString()));
            }

            return Futures.immediateFuture(true);
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.thingsboard.server.dao.nosql.CassandraAbstractModelDao.java

protected ListenableFuture<D> findOneByStatementAsync(TenantId tenantId, Statement statement) {
    if (statement != null) {
        statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
        ResultSetFuture resultSetFuture = executeAsyncRead(tenantId, statement);
        return Futures.transform(resultSetFuture, new Function<ResultSet, D>() {
            @Nullable//from  w w w .  j av  a2  s .  c om
            @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);
}

From source file:com.facebook.buck.artifact_cache.DirArtifactCache.java

@Override
public ListenableFuture<Void> store(ArtifactInfo info, BorrowablePath output) {

    if (!doStore) {
        return Futures.immediateFuture(null);
    }//from w  w w  .  j av a  2  s .  co  m

    try {
        Optional<Path> borrowedAndStoredArtifactPath = Optional.empty();
        for (RuleKey ruleKey : info.getRuleKeys()) {
            Path artifactPath = getPathForRuleKey(ruleKey, Optional.empty());
            Path metadataPath = getPathForRuleKey(ruleKey, Optional.of(".metadata"));

            if (filesystem.exists(artifactPath) && filesystem.exists(metadataPath)) {
                continue;
            }

            filesystem.mkdirs(getParentDirForRuleKey(ruleKey));

            if (!output.canBorrow()) {
                storeArtifactOutput(output.getPath(), artifactPath);
            } else {
                // This branch means that we are apparently the only users of the `output`, so instead
                // of making a safe transfer of the output to the dir cache (copy+move), we can just
                // move it without copying.  This significantly optimizes the Disk I/O.
                if (!borrowedAndStoredArtifactPath.isPresent()) {
                    borrowedAndStoredArtifactPath = Optional.of(artifactPath);
                    filesystem.move(output.getPath(), artifactPath, StandardCopyOption.REPLACE_EXISTING);
                } else {
                    storeArtifactOutput(borrowedAndStoredArtifactPath.get(), artifactPath);
                }
            }
            bytesSinceLastDeleteOldFiles += filesystem.getFileSize(artifactPath);

            // Now, write the meta data artifact.
            Path tmp = filesystem.createTempFile(getPreparedTempFolder(), "metadata", TMP_EXTENSION);
            try {
                try (DataOutputStream out = new DataOutputStream(filesystem.newFileOutputStream(tmp))) {
                    out.writeInt(info.getMetadata().size());
                    for (Map.Entry<String, String> ent : info.getMetadata().entrySet()) {
                        out.writeUTF(ent.getKey());
                        byte[] val = ent.getValue().getBytes(Charsets.UTF_8);
                        out.writeInt(val.length);
                        out.write(val);
                    }
                }
                filesystem.move(tmp, metadataPath, StandardCopyOption.REPLACE_EXISTING);
                bytesSinceLastDeleteOldFiles += filesystem.getFileSize(metadataPath);
            } finally {
                filesystem.deleteFileAtPathIfExists(tmp);
            }
        }

    } catch (IOException e) {
        LOG.warn(e, "Artifact store(%s, %s) error", info.getRuleKeys(), output);
    }

    if (maxCacheSizeBytes.isPresent() && bytesSinceLastDeleteOldFiles > (maxCacheSizeBytes.get()
            * STORED_TO_MAX_BYTES_RATIO_TRIM_TRIGGER)) {
        bytesSinceLastDeleteOldFiles = 0L;
        deleteOldFiles();
    }

    return Futures.immediateFuture(null);
}

From source file:producerstest.SimpleProducerModule.java

@Produces
@IntoSet/*from w ww  .  j a  v a  2  s.  co  m*/
@SuppressWarnings("unused") // unthrown exception for test
static ListenableFuture<String> setOfStrFutureElementThrowingException() throws IOException {
    return Futures.immediateFuture("set of str element throwing exception");
}