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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input,
        AsyncFunction<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future .

Usage

From source file:com.google.gapid.server.Client.java

public ListenableFuture<Path.Capture> loadCapture(String path) {
    LOG.log(FINE, "RPC->loadCapture({0})", path);
    return Futures.transformAsync(client.loadCapture(LoadCaptureRequest.newBuilder().setPath(path).build()),
            in -> Futures.immediateFuture(throwIfError(in.getCapture(), in.getError())));
}

From source file:com.google.gapid.server.Client.java

public ListenableFuture<List<Path.Device>> getDevices() {
    LOG.log(FINE, "RPC->getDevices()");
    return Futures.transformAsync(client.getDevices(GetDevicesRequest.newBuilder().build()),
            in -> Futures.immediateFuture(throwIfError(in.getDevices(), in.getError()).getListList()));
}

From source file:com.google.gapid.server.Client.java

public ListenableFuture<List<Path.Device>> getDevicesForReplay(Path.Capture capture) {
    LOG.log(FINE, "RPC->getDevicesForReplay({0})", capture);
    return Futures.transformAsync(
            client.getDevicesForReplay(GetDevicesForReplayRequest.newBuilder().setCapture(capture).build()),
            in -> Futures.immediateFuture(throwIfError(in.getDevices(), in.getError()).getListList()));
}

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

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

    return Futures.transformAsync(attemptTwoLevelStore(info, output), input -> {
        if (input) {
            return Futures.immediateFuture(null);
        }/* w w  w . j  av a2 s  .c  om*/
        return delegate.store(info, output);
    });
}

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

private ListenableFuture<Boolean> attemptTwoLevelStore(final ArtifactInfo info, final BorrowablePath output) {

    return Futures.transformAsync(Futures.immediateFuture(null), (AsyncFunction<Void, Boolean>) input -> {
        long fileSize = projectFilesystem.getFileSize(output.getPath());

        if (!performTwoLevelStores || fileSize < minimumTwoLevelStoredArtifactSize
                || (maximumTwoLevelStoredArtifactSize.isPresent()
                        && fileSize > maximumTwoLevelStoredArtifactSize.get())) {
            return Futures.immediateFuture(false);
        }//from w  w  w . j  a  va 2 s .  c o m

        long hashComputationStart = System.currentTimeMillis();
        String hashCode = projectFilesystem.computeSha1(output.getPath()) + "2c00";
        long hashComputationEnd = System.currentTimeMillis();
        secondLevelHashComputationTimeMs.addSample(hashComputationEnd - hashComputationStart);

        ImmutableMap<String, String> metadataWithCacheKey = ImmutableMap.<String, String>builder()
                .putAll(info.getMetadata()).put(METADATA_KEY, hashCode).build();

        return Futures
                .transform(Futures.allAsList(
                        delegate.store(
                                ArtifactInfo.builder().setRuleKeys(info.getRuleKeys())
                                        .setMetadata(metadataWithCacheKey).build(),
                                BorrowablePath.notBorrowablePath(emptyFilePath)),
                        delegate.store(ArtifactInfo.builder().addRuleKeys(new RuleKey(hashCode)).build(),
                                output)),
                        Functions.constant(true));
    });
}

From source file:com.google.gapid.server.Client.java

public ListenableFuture<Path.ImageInfo> getFramebufferAttachment(Path.Device device, Path.Command after,
        GfxAPI.FramebufferAttachment attachment, Service.RenderSettings settings) {
    LOG.log(FINE, "RPC->getFramebufferAttachment({0}, {1}, {2}, {3})",
            new Object[] { device, after, attachment, settings });
    return Futures.transformAsync(
            client.getFramebufferAttachment(GetFramebufferAttachmentRequest.newBuilder().setDevice(device)
                    .setAfter(after).setAttachment(attachment).setSettings(settings).build()),
            in -> Futures.immediateFuture(throwIfError(in.getImage(), in.getError())));
}

From source file:com.google.gapid.views.CommandTree.java

private void search(String text, boolean regex) {
    models.analytics.postInteraction(View.Commands, ClientAction.Search);
    CommandStream.Node parent = models.commands.getData();
    if (parent != null && !text.isEmpty()) {
        CommandStream.Node selection = tree.getSelection();
        if (selection != null) {
            parent = selection;//from www  .j a  v  a  2  s. co  m
        }
        searchController.start().listen(
                Futures.transformAsync(search(searchRequest(parent, text, regex)),
                        r -> getTreePath(models.commands.getData(), Lists.newArrayList(),
                                r.getCommandTreeNode().getIndicesList().iterator())),
                new UiCallback<TreePath, TreePath>(tree, LOG) {
                    @Override
                    protected TreePath onRpcThread(Rpc.Result<TreePath> result)
                            throws RpcException, ExecutionException {
                        return result.get();
                    }

                    @Override
                    protected void onUiThread(TreePath result) {
                        select(result);
                    }
                });
    }
}

From source file:me.grapebaba.hyperledger.fabric.MemberServiceImpl.java

@Override
public ListenableFuture<Enrollment> enroll(EnrollmentRequest enrollmentRequest) {
    Preconditions.checkNotNull(enrollmentRequest.getEnrollmentID());
    Preconditions.checkNotNull(enrollmentRequest.getEnrollmentSecret());

    final KeyPair signingKeyPair = crypto.ecdsaKeyGen();
    PublicKey signingPublicKey = signingKeyPair.getPublic();

    final KeyPair encryptionKeyPair = crypto.ecdsaKeyGen();
    PublicKey encryptionPublicKey = encryptionKeyPair.getPublic();

    final Timestamp timestamp = Timestamp.newBuilder().setSeconds(System.currentTimeMillis() / 1000).setNanos(0)
            .build();//from  w w w  . ja v a  2s.c  o m
    final Ca.Identity id = Ca.Identity.newBuilder().setId(enrollmentRequest.getEnrollmentID()).build();
    final Ca.Token tok = Ca.Token.newBuilder()
            .setTok(ByteString.copyFrom(enrollmentRequest.getEnrollmentSecret(), Charset.defaultCharset()))
            .build();
    final Ca.PublicKey signingPubKey = Ca.PublicKey.newBuilder().setType(Ca.CryptoType.ECDSA)
            .setKey(ByteString.copyFrom(signingPublicKey.getEncoded())).build();
    final Ca.PublicKey encryptionPubKey = Ca.PublicKey.newBuilder().setType(Ca.CryptoType.ECDSA)
            .setKey(ByteString.copyFrom(encryptionPublicKey.getEncoded())).build();
    final Ca.ECertCreateReq eCertCreateReq = Ca.ECertCreateReq.newBuilder().setId(id).setTok(tok)
            .setTs(timestamp).setSign(signingPubKey).setEnc(encryptionPubKey).buildPartial();

    ListenableFuture<ByteString> updatedTokenFuture = Futures.transform(
            ecapStub.createCertificatePair(eCertCreateReq), new Function<Ca.ECertCreateResp, ByteString>() {
                @Nullable
                @Override
                public ByteString apply(@Nullable Ca.ECertCreateResp input) {
                    return crypto.eciesDecrypt(encryptionKeyPair.getPrivate(), input.getTok().getTok());
                }
            });

    ListenableFuture<Ca.ECertCreateResp> eCertCreateResp = Futures.transformAsync(updatedTokenFuture,
            new AsyncFunction<ByteString, Ca.ECertCreateResp>() {
                @Override
                public ListenableFuture<Ca.ECertCreateResp> apply(@Nullable ByteString input) throws Exception {
                    final Ca.Token tok = Ca.Token.newBuilder().setTok(input).build();
                    ByteString origin = eCertCreateReq.toBuilder().setTok(tok).buildPartial().toByteString();
                    BigInteger[] sig = crypto.ecdsaSign(signingKeyPair.getPrivate(), origin);
                    Ca.Signature signature = Ca.Signature.newBuilder()
                            .setR(ByteString.copyFrom(BigIntegers.asUnsignedByteArray(sig[0])))
                            .setS(ByteString.copyFrom(BigIntegers.asUnsignedByteArray(sig[1])))
                            .setType(Ca.CryptoType.ECDSA).build();

                    return ecapStub.createCertificatePair(eCertCreateReq.toBuilder().setSig(signature).build());
                }
            });

    return Futures.transform(eCertCreateResp, new Function<Ca.ECertCreateResp, Enrollment>() {
        @Nullable
        @Override
        public Enrollment apply(@Nullable Ca.ECertCreateResp input) {
            return Enrollment.newBuilder().withKey(signingKeyPair.getPrivate())
                    .withCert(input.getCerts().getSign()).withChainKey(input.getPkchain()).build();
        }
    });
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processPartitions(final List<QualifiedName> qNames) {
    final List<QualifiedName> excludeQualifiedNames = config.getElasticSearchRefreshExcludeQualifiedNames();
    final List<String> tables = elasticSearchUtil.getTableIdsByCatalogs(ElasticSearchDoc.Type.table.name(),
            qNames, excludeQualifiedNames);
    final List<ListenableFuture<ListenableFuture<Void>>> futures = tables.stream()
            .map(s -> service.submit(() -> {
                final QualifiedName tableName = QualifiedName.fromString(s, false);
                final List<ListenableFuture<Void>> indexFutures = Lists.newArrayList();
                int offset = 0;
                int count;
                Sort sort;//from   ww  w .ja  va  2  s .c o m
                if ("s3".equals(tableName.getCatalogName()) || "aegisthus".equals(tableName.getCatalogName())) {
                    sort = new Sort("id", SortOrder.ASC);
                } else {
                    sort = new Sort("part_id", SortOrder.ASC);
                }
                final Pageable pageable = new Pageable(10000, offset);
                do {
                    final List<PartitionDto> partitionDtos = partitionService.list(tableName, null, null, sort,
                            pageable, true, true, true);
                    count = partitionDtos.size();
                    if (!partitionDtos.isEmpty()) {
                        final List<List<PartitionDto>> partitionedPartitionDtos = Lists.partition(partitionDtos,
                                1000);
                        partitionedPartitionDtos.forEach(subPartitionsDtos -> indexFutures
                                .add(indexPartitionDtos(tableName, subPartitionsDtos)));
                        offset = offset + count;
                        pageable.setOffset(offset);
                    }
                } while (count == 10000);
                return Futures.transform(Futures.successfulAsList(indexFutures),
                        Functions.constant((Void) null));
            })).collect(Collectors.toList());
    final ListenableFuture<Void> processPartitionsFuture = Futures
            .transformAsync(Futures.successfulAsList(futures), input -> {
                final List<ListenableFuture<Void>> inputFuturesWithoutNulls = input.stream().filter(NOT_NULL)
                        .collect(Collectors.toList());
                return Futures.transform(Futures.successfulAsList(inputFuturesWithoutNulls),
                        Functions.constant(null));
            });
    return Futures.transformAsync(processPartitionsFuture, input -> {
        elasticSearchUtil.refresh();
        final List<ListenableFuture<Void>> cleanUpFutures = tables.stream()
                .map(s -> service.submit(
                        () -> partitionsCleanUp(QualifiedName.fromString(s, false), excludeQualifiedNames)))
                .collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(cleanUpFutures), Functions.constant(null));
    });
}

From source file:org.thingsboard.server.dao.entityview.EntityViewServiceImpl.java

@Override
public ListenableFuture<List<EntityView>> findEntityViewsByQuery(TenantId tenantId,
        EntityViewSearchQuery query) {/*from w w w  . j  ava  2s.  co  m*/
    ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(tenantId,
            query.toEntitySearchQuery());
    ListenableFuture<List<EntityView>> entityViews = Futures.transformAsync(relations, r -> {
        EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection();
        List<ListenableFuture<EntityView>> futures = new ArrayList<>();
        for (EntityRelation relation : r) {
            EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom();
            if (entityId.getEntityType() == EntityType.ENTITY_VIEW) {
                futures.add(findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId())));
            }
        }
        return Futures.successfulAsList(futures);
    });

    entityViews = Futures.transform(entityViews, new Function<List<EntityView>, List<EntityView>>() {
        @Nullable
        @Override
        public List<EntityView> apply(@Nullable List<EntityView> entityViewList) {
            return entityViewList == null ? Collections.emptyList()
                    : entityViewList.stream()
                            .filter(entityView -> query.getEntityViewTypes().contains(entityView.getType()))
                            .collect(Collectors.toList());
        }
    });

    return entityViews;
}