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

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

Introduction

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

Prototype

public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
        Function<? super I, ? extends O> function) 

Source Link

Document

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future .

Usage

From source file:org.thingsboard.server.service.script.RemoteJsInvokeService.java

@Override
protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, String functionName, Object[] args) {
    String scriptBody = scriptIdToBodysMap.get(scriptId);
    if (scriptBody == null) {
        return Futures.immediateFailedFuture(
                new RuntimeException("No script body found for scriptId: [" + scriptId + "]!"));
    }/*ww  w.j  ava  2 s. com*/
    JsInvokeProtos.JsInvokeRequest.Builder jsRequestBuilder = JsInvokeProtos.JsInvokeRequest.newBuilder()
            .setScriptIdMSB(scriptId.getMostSignificantBits())
            .setScriptIdLSB(scriptId.getLeastSignificantBits()).setFunctionName(functionName)
            .setTimeout((int) maxRequestsTimeout).setScriptBody(scriptIdToBodysMap.get(scriptId));

    for (int i = 0; i < args.length; i++) {
        jsRequestBuilder.addArgs(args[i].toString());
    }

    JsInvokeProtos.RemoteJsRequest jsRequestWrapper = JsInvokeProtos.RemoteJsRequest.newBuilder()
            .setInvokeRequest(jsRequestBuilder.build()).build();

    ListenableFuture<JsInvokeProtos.RemoteJsResponse> future = kafkaTemplate.post(scriptId.toString(),
            jsRequestWrapper);
    return Futures.transform(future, response -> {
        JsInvokeProtos.JsInvokeResponse invokeResult = response.getInvokeResponse();
        if (invokeResult.getSuccess()) {
            return invokeResult.getResult();
        } else {
            log.debug("[{}] Failed to compile script due to [{}]: {}", scriptId,
                    invokeResult.getErrorCode().name(), invokeResult.getErrorDetails());
            throw new RuntimeException(invokeResult.getErrorDetails());
        }
    });
}

From source file:org.opendaylight.openflowplugin.impl.services.batch.FlatBatchFlowAdapters.java

/**
 * shortcut for {@link #convertBatchFlowResult(int)} with conversion {@link ListenableFuture}
 *
 * @param <T>                    exact type of batch flow output
 * @param resultUpdateFlowFuture batch flow rpc-result (add/remove/update)
 * @param currentOffset          offset of current batch plan step with respect to entire chain of steps
 * @return ListenableFuture with converted result {@link ProcessFlatBatchOutput}
 *///  w  w  w.  j a  v  a 2  s .  c  o m
public static <T extends BatchFlowOutputListGrouping> ListenableFuture<RpcResult<ProcessFlatBatchOutput>> convertFlowBatchFutureForChain(
        final Future<RpcResult<T>> resultUpdateFlowFuture, final int currentOffset) {
    return Futures.transform(JdkFutureAdapters.listenInPoolThread(resultUpdateFlowFuture),
            FlatBatchFlowAdapters.<T>convertBatchFlowResult(currentOffset));
}

From source file:com.continuuity.weave.internal.kafka.client.KafkaBrokerCache.java

private void getTopic(final String path, final String topic) {
    Futures.addCallback(zkClient.getChildren(path, new Watcher() {
        @Override/* w w  w .  ja  va  2 s  . c  o  m*/
        public void process(WatchedEvent event) {
            // Other event type changes are either could be ignored or handled by parent watcher
            if (event.getType() == Event.EventType.NodeChildrenChanged) {
                getTopic(path, topic);
            }
        }
    }), new FutureCallback<NodeChildren>() {
        @Override
        public void onSuccess(NodeChildren result) {
            List<String> children = result.getChildren();
            final List<ListenableFuture<BrokerPartition>> futures = Lists
                    .newArrayListWithCapacity(children.size());

            // Fetch data from each broken node
            for (final String brokerId : children) {
                Futures.transform(zkClient.getData(path + "/" + brokerId),
                        new Function<NodeData, BrokerPartition>() {
                            @Override
                            public BrokerPartition apply(NodeData input) {
                                return new BrokerPartition(brokerId,
                                        Integer.parseInt(new String(input.getData(), Charsets.UTF_8)));
                            }
                        });
            }

            // When all fetching is done, build the partition size->broker map for this topic
            Futures.successfulAsList(futures).addListener(new Runnable() {
                @Override
                public void run() {
                    Map<Integer, Set<String>> partitionBrokers = Maps.newHashMap();
                    for (ListenableFuture<BrokerPartition> future : futures) {
                        try {
                            BrokerPartition info = future.get();
                            Set<String> brokerSet = partitionBrokers.get(info.getPartitionSize());
                            if (brokerSet == null) {
                                brokerSet = Sets.newHashSet();
                                partitionBrokers.put(info.getPartitionSize(), brokerSet);
                            }
                            brokerSet.add(info.getBrokerId());
                        } catch (Exception e) {
                            // Exception is ignored, as it will be handled by parent watcher
                        }
                    }
                    topicBrokers.put(topic, ImmutableSortedMap.copyOf(partitionBrokers));
                }
            }, Threads.SAME_THREAD_EXECUTOR);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op. Failure would be handled by parent watcher already (e.g. node not exists -> children change in parent)
        }
    });
}

From source file:org.opendaylight.openflowplugin.impl.services.batch.FlatBatchGroupAdapters.java

/**
 * shortcut for {@link #convertBatchGroupResult(int)} with conversion {@link ListenableFuture}
 *
 * @param <T>                     exact type of batch flow output
 * @param resultUpdateGroupFuture batch group rpc-result (add/remove/update)
 * @param currentOffset           offset of current batch plan step with respect to entire chain of steps
 * @return ListenableFuture with converted result {@link ProcessFlatBatchOutput}
 *///from  w w  w  . j  av a 2  s  .  com
public static <T extends BatchGroupOutputListGrouping> ListenableFuture<RpcResult<ProcessFlatBatchOutput>> convertGroupBatchFutureForChain(
        final Future<RpcResult<T>> resultUpdateGroupFuture, final int currentOffset) {
    return Futures.transform(JdkFutureAdapters.listenInPoolThread(resultUpdateGroupFuture),
            FlatBatchGroupAdapters.<T>convertBatchGroupResult(currentOffset));
}

From source file:org.opendaylight.openflowplugin.impl.services.batch.FlatBatchMeterAdapters.java

/**
 * shortcut for {@link #convertBatchMeterResult(int)} with conversion {@link ListenableFuture}
 *
 * @param <T>                     exact type of batch flow output
 * @param resultUpdateMeterFuture batch group rpc-result (add/remove/update)
 * @param currentOffset           offset of current batch plan step with respect to entire chain of steps
 * @return ListenableFuture with converted result {@link ProcessFlatBatchOutput}
 *//*w  w  w .  ja va2s  .  c o m*/
public static <T extends BatchMeterOutputListGrouping> ListenableFuture<RpcResult<ProcessFlatBatchOutput>> convertMeterBatchFutureForChain(
        final Future<RpcResult<T>> resultUpdateMeterFuture, final int currentOffset) {
    return Futures.transform(JdkFutureAdapters.listenInPoolThread(resultUpdateMeterFuture),
            FlatBatchMeterAdapters.<T>convertBatchMeterResult(currentOffset));
}

From source file:com.spotify.asyncdatastoreclient.Datastore.java

/**
 * Start a new transaction.//from   w w  w . ja v a  2 s . c om
 *
 * The returned {@code TransactionResult} contains the transaction if the
 * request is successful.
 *
 * @param isolationLevel the transaction isolation level to request.
 * @return the result of the transaction request.
 */
public ListenableFuture<TransactionResult> transactionAsync(final IsolationLevel isolationLevel) {
    final ListenableFuture<Response> httpResponse;
    try {
        final DatastoreV1.BeginTransactionRequest.Builder request = DatastoreV1.BeginTransactionRequest
                .newBuilder();
        if (isolationLevel == IsolationLevel.SERIALIZABLE) {
            request.setIsolationLevel(DatastoreV1.BeginTransactionRequest.IsolationLevel.SERIALIZABLE);
        } else {
            request.setIsolationLevel(DatastoreV1.BeginTransactionRequest.IsolationLevel.SNAPSHOT);
        }
        final ProtoHttpContent payload = new ProtoHttpContent(request.build());
        httpResponse = ListenableFutureAdapter
                .asGuavaFuture(prepareRequest("beginTransaction", payload).execute());
    } catch (final Exception e) {
        return Futures.immediateFailedFuture(new DatastoreException(e));
    }
    return Futures.transform(httpResponse, (Response response) -> {
        if (!isSuccessful(response.getStatusCode())) {
            throw new DatastoreException(response.getStatusCode(), response.getResponseBody());
        }
        final DatastoreV1.BeginTransactionResponse transaction = DatastoreV1.BeginTransactionResponse
                .parseFrom(streamResponse(response));
        return Futures.immediateFuture(TransactionResult.build(transaction));
    });
}

From source file:me.j360.trace.storage.elasticsearch.ElasticsearchSpanStore.java

@Override
public ListenableFuture<List<Span>> getRawTrace(long traceId) {
    SearchRequestBuilder elasticRequest = client.prepareSearch(indexNameFormatter.catchAll())
            .setTypes(ElasticsearchConstants.SPAN).setSize(MAX_RAW_SPANS)
            .setQuery(termQuery("traceId", Util.toLowerHex(traceId)));

    return Futures.transform(ElasticFutures.toGuava(elasticRequest.execute()),
            new Function<SearchResponse, List<Span>>() {
                @Override//from  w  w  w . j a v a  2  s . c  o  m
                public List<Span> apply(SearchResponse response) {
                    if (response.getHits().totalHits() == 0) {
                        return null;
                    }
                    ImmutableList.Builder<Span> trace = ImmutableList.builder();
                    for (SearchHit hit : response.getHits()) {
                        trace.add(Codec.JSON.readSpan(hit.getSourceRef().toBytes()));
                    }
                    return trace.build();
                }
            });
}

From source file:org.thingsboard.server.dao.sql.timeseries.JpaTimeseriesDao.java

private ListenableFuture<Optional<TsKvEntry>> findAndAggregateAsync(EntityId entityId, String key, long startTs,
        long endTs, long ts, Aggregation aggregation) {
    CompletableFuture<TsKvEntity> entity;
    String entityIdStr = fromTimeUUID(entityId.getId());
    switch (aggregation) {
    case AVG:/*from   w w w  . j a va2s  .  c om*/
        entity = tsKvRepository.findAvg(entityIdStr, entityId.getEntityType(), key, startTs, endTs);

        break;
    case MAX:
        entity = tsKvRepository.findMax(entityIdStr, entityId.getEntityType(), key, startTs, endTs);

        break;
    case MIN:
        entity = tsKvRepository.findMin(entityIdStr, entityId.getEntityType(), key, startTs, endTs);

        break;
    case SUM:
        entity = tsKvRepository.findSum(entityIdStr, entityId.getEntityType(), key, startTs, endTs);

        break;
    case COUNT:
        entity = tsKvRepository.findCount(entityIdStr, entityId.getEntityType(), key, startTs, endTs);

        break;
    default:
        throw new IllegalArgumentException("Not supported aggregation type: " + aggregation);
    }

    SettableFuture<TsKvEntity> listenableFuture = SettableFuture.create();
    entity.whenComplete((tsKvEntity, throwable) -> {
        if (throwable != null) {
            listenableFuture.setException(throwable);
        } else {
            listenableFuture.set(tsKvEntity);
        }
    });
    return Futures.transform(listenableFuture, new Function<TsKvEntity, Optional<TsKvEntry>>() {
        @Override
        public Optional<TsKvEntry> apply(@Nullable TsKvEntity entity) {
            if (entity != null && entity.isNotEmpty()) {
                entity.setEntityId(entityIdStr);
                entity.setEntityType(entityId.getEntityType());
                entity.setKey(key);
                entity.setTs(ts);
                return Optional.of(DaoUtil.getData(entity));
            } else {
                return Optional.empty();
            }
        }
    });
}

From source file:org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker.java

public ListenableFuture<RpcResult<TransactionStatus>> commit(final ForwardedBackwardsCompatibleTransacion tx) {

    final List<DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject>> subTrans = new ArrayList<>();
    LOG.debug("Tx: {} Submitted.", tx.getIdentifier());
    ListenableFuture<Boolean> requestCommit = executorService.submit(new Callable<Boolean>() {

        @Override//www.j  a va  2  s .co  m
        public Boolean call() throws Exception {
            try {
                for (CommitHandlerRegistrationImpl handler : commitHandlers.values()) {

                    DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> subTx = handler
                            .getInstance().requestCommit(tx);
                    subTrans.add(subTx);
                }
            } catch (Exception e) {
                LOG.error("Tx: {} Rollback.", tx.getIdentifier(), e);
                for (DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> subTx : subTrans) {
                    subTx.rollback();
                }
                return false;
            }
            LOG.debug("Tx: {} Can Commit True.", tx.getIdentifier());
            return true;
        }

    });

    ListenableFuture<RpcResult<TransactionStatus>> dataStoreCommit = Futures.transform(requestCommit,
            new AsyncFunction<Boolean, RpcResult<TransactionStatus>>() {

                @Override
                public ListenableFuture<RpcResult<TransactionStatus>> apply(final Boolean requestCommitSuccess)
                        throws Exception {
                    if (requestCommitSuccess) {
                        return AbstractDataTransaction.convertToLegacyCommitFuture(tx.getDelegate().submit());
                    }
                    return Futures.immediateFuture(RpcResultBuilder.<TransactionStatus>failed()
                            .withResult(TransactionStatus.FAILED).build());
                }
            });

    return Futures.transform(dataStoreCommit,
            new Function<RpcResult<TransactionStatus>, RpcResult<TransactionStatus>>() {
                @Override
                public RpcResult<TransactionStatus> apply(final RpcResult<TransactionStatus> input) {
                    if (input.isSuccessful()) {
                        for (DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> subTx : subTrans) {
                            subTx.finish();
                        }
                    } else {
                        LOG.error("Tx: {} Rollback - Datastore commit failed.", tx.getIdentifier());
                        for (DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> subTx : subTrans) {
                            subTx.rollback();
                        }
                    }
                    return input;
                }
            });
}

From source file:org.thingsboard.server.dao.rule.BaseRuleService.java

@Override
public ListenableFuture<RuleMetaData> findRuleByIdAsync(RuleId ruleId) {
    validateId(ruleId, "Incorrect rule id for search rule request.");
    ListenableFuture<RuleMetaDataEntity> ruleEntity = ruleDao.findByIdAsync(ruleId.getId());
    return Futures.transform(ruleEntity,
            (com.google.common.base.Function<? super RuleMetaDataEntity, ? extends RuleMetaData>) input -> getData(
                    input));//from w  w w. ja va 2s.  co  m
}