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, Executor executor) 

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.opendaylight.groupbasedpolicy.endpoint.AbstractEndpointRegistry.java

@Override
public Future<RpcResult<Void>> registerEndpoint(RegisterEndpointInput input) {
    long timestamp = System.currentTimeMillis();

    WriteTransaction t = dataProvider.newWriteOnlyTransaction();

    if (input.getL2Context() != null && input.getMacAddress() != null) {
        Endpoint ep = buildEndpoint(input).setTimestamp(timestamp).build();

        EndpointKey key = new EndpointKey(ep.getL2Context(), ep.getMacAddress());
        InstanceIdentifier<Endpoint> iid = InstanceIdentifier.builder(Endpoints.class)
                .child(Endpoint.class, key).build();
        t.put(LogicalDatastoreType.OPERATIONAL, iid, ep);
    }//from   w w  w  .  ja  v a 2  s  .  c om
    if (input.getL3Address() != null) {
        for (L3Address l3addr : input.getL3Address()) {
            EndpointL3Key key3 = new EndpointL3Key(l3addr.getIpAddress(), l3addr.getL3Context());
            EndpointL3 ep3 = buildEndpointL3(input).setIpAddress(key3.getIpAddress())
                    .setL3Context(key3.getL3Context()).setTimestamp(timestamp).build();
            InstanceIdentifier<EndpointL3> iid_l3 = InstanceIdentifier.builder(Endpoints.class)
                    .child(EndpointL3.class, key3).build();
            t.put(LogicalDatastoreType.OPERATIONAL, iid_l3, ep3);
        }
    }
    ListenableFuture<Void> r = t.submit();
    return Futures.transform(r, futureTrans, executor);
}

From source file:org.opendaylight.faas.fabric.general.EndPointRegister.java

@Override
public Future<RpcResult<Void>> locateEndpoint(LocateEndpointInput input) {

    final RpcResult<Void> result = RpcResultBuilder.<Void>success().build();

    if (input == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }/*from www. j a v a 2  s.co m*/
    final Uuid epId = input.getEndpointId();

    if (epId == null) {
        return Futures.immediateFailedCheckedFuture(new IllegalArgumentException("endpoint can not be empty!"));
    }
    final FabricId fabricid = input.getFabricId();
    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricid);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("fabric is not exist!"));
    }

    ReadWriteTransaction trans = dataBroker.newReadWriteTransaction();

    EndpointBuilder epBuilder = new EndpointBuilder();
    LocationBuilder locBuilder = new LocationBuilder(input.getLocation());
    epBuilder.setEndpointUuid(epId);
    epBuilder.setLocation(locBuilder.build());

    final InstanceIdentifier<Endpoint> eppath = Constants.DOM_ENDPOINTS_PATH.child(Endpoint.class,
            new EndpointKey(epId));
    trans.merge(LogicalDatastoreType.OPERATIONAL, eppath, epBuilder.build());

    CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();

    return Futures.transform(future, new AsyncFunction<Void, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Void input) throws Exception {
            return Futures.immediateFuture(result);
        }
    }, executor);
}

From source file:org.jclouds.atmos.internal.StubAtmosAsyncClient.java

@Override
public ListenableFuture<AtmosObject> headFile(String path) {
    String container = path.substring(0, path.indexOf('/'));
    path = path.substring(path.indexOf('/') + 1);
    try {/*from  w w w .j  a v  a2  s . c  om*/
        return Futures.transform(blobStore.getBlob(container, path), blob2Object, userExecutor);
    } catch (Exception e) {
        return immediateFailedFuture(Throwables.getRootCause(e));
    }
}

From source file:org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java

@Override
protected ListenableFuture<AtomicReference<NodeMetadata>> createNodeInGroupWithNameAndTemplate(String group,
        final String name, Template template) {

    ListenableFuture<AtomicReference<NodeMetadata>> future = super.createNodeInGroupWithNameAndTemplate(group,
            name, template);//from   ww w  .j  a v a 2s .c  om
    NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions());

    if (templateOptions.shouldAutoAssignFloatingIp()) {
        return Futures.transform(future, createAndAddFloatingIpToNode, userExecutor);
    } else {
        return future;
    }
}

From source file:io.prestosql.plugin.hive.HivePageSink.java

private ListenableFuture<Collection<Slice>> doFinish() {
    ImmutableList.Builder<Slice> partitionUpdates = ImmutableList.builder();
    List<Callable<Object>> verificationTasks = new ArrayList<>();
    for (HiveWriter writer : writers) {
        writer.commit();/* www . ja  va 2s  . c o  m*/
        PartitionUpdate partitionUpdate = writer.getPartitionUpdate();
        partitionUpdates.add(wrappedBuffer(partitionUpdateCodec.toJsonBytes(partitionUpdate)));
        writer.getVerificationTask().map(Executors::callable).ifPresent(verificationTasks::add);
    }
    List<Slice> result = partitionUpdates.build();

    writtenBytes = writers.stream().mapToLong(HiveWriter::getWrittenBytes).sum();
    validationCpuNanos = writers.stream().mapToLong(HiveWriter::getValidationCpuNanos).sum();

    if (verificationTasks.isEmpty()) {
        return Futures.immediateFuture(result);
    }

    try {
        List<ListenableFuture<?>> futures = writeVerificationExecutor.invokeAll(verificationTasks).stream()
                .map(future -> (ListenableFuture<?>) future).collect(toList());
        return Futures.transform(Futures.allAsList(futures), input -> result, directExecutor());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}

From source file:org.jclouds.atmos.internal.StubAtmosAsyncClient.java

@Override
public ListenableFuture<BoundedSet<? extends DirectoryEntry>> listDirectories(ListOptions... optionsList) {
    // org.jclouds.blobstore.options.ListOptions options = container2ContainerListOptions
    // .apply(optionsList);
    return Futures.transform(blobStore.list(), resource2ObjectList, userExecutor);
}

From source file:com.facebook.presto.server.protocol.StatementResource.java

private void asyncQueryResults(Query query, OptionalLong token, Duration maxWait, DataSize targetResultSize,
        UriInfo uriInfo, String scheme, AsyncResponse asyncResponse) {
    Duration wait = WAIT_ORDERING.min(MAX_WAIT_TIME, maxWait);
    if (targetResultSize == null) {
        targetResultSize = DEFAULT_TARGET_RESULT_SIZE;
    } else {/*  w  w  w . ja v  a  2  s .  com*/
        targetResultSize = Ordering.natural().min(targetResultSize, MAX_TARGET_RESULT_SIZE);
    }
    ListenableFuture<QueryResults> queryResultsFuture = query.waitForResults(token, uriInfo, scheme, wait,
            targetResultSize);

    ListenableFuture<Response> response = Futures.transform(queryResultsFuture,
            queryResults -> toResponse(query, queryResults), directExecutor());

    bindAsyncResponse(asyncResponse, response, responseExecutor);
}

From source file:org.glowroot.central.util.Session.java

public ListenableFuture<ResultSet> readAsyncWarnIfNoRows(Statement statement, String warningMessage,
        Object... warningArguments) throws Exception {
    return Futures.transform(readAsync(statement), new Function<ResultSet, ResultSet>() {
        @Override//from   w  ww  .j a v a2 s.com
        public ResultSet apply(ResultSet results) {
            if (results.isExhausted()) {
                logger.warn(warningMessage, warningArguments);
            }
            return results;
        }
    }, MoreExecutors.directExecutor());
}

From source file:org.thingsboard.server.dao.timeseries.CassandraBaseTimeseriesDao.java

private ListenableFuture<List<Long>> getPartitionsFuture(TenantId tenantId, ReadTsKvQuery query,
        EntityId entityId, long minPartition, long maxPartition) {
    if (isFixedPartitioning()) { //no need to fetch partitions from DB
        return Futures.immediateFuture(FIXED_PARTITION);
    }/*from  w w  w. j a  v a  2s .co m*/
    ResultSetFuture partitionsFuture = fetchPartitions(tenantId, entityId, query.getKey(), minPartition,
            maxPartition);
    return Futures.transform(partitionsFuture, getPartitionsArrayFunction(), readResultsProcessingExecutor);
}

From source file:org.opendaylight.groupbasedpolicy.endpoint.AbstractEndpointRegistry.java

@Override
public Future<RpcResult<Void>> unregisterEndpoint(UnregisterEndpointInput input) {
    WriteTransaction t = dataProvider.newWriteOnlyTransaction();
    if (input.getL2() != null) {
        for (L2 l2a : input.getL2()) {
            EndpointKey key = new EndpointKey(l2a.getL2Context(), l2a.getMacAddress());
            InstanceIdentifier<Endpoint> iid = InstanceIdentifier.builder(Endpoints.class)
                    .child(Endpoint.class, key).build();
            t.delete(LogicalDatastoreType.OPERATIONAL, iid);
        }/*from  w  w w .  jav a2 s. co  m*/
    }
    if (input.getL3() != null) {
        for (L3 l3addr : input.getL3()) {
            EndpointL3Key key3 = new EndpointL3Key(l3addr.getIpAddress(), l3addr.getL3Context());
            InstanceIdentifier<EndpointL3> iid_l3 = InstanceIdentifier.builder(Endpoints.class)
                    .child(EndpointL3.class, key3).build();
            t.delete(LogicalDatastoreType.OPERATIONAL, iid_l3);
        }
    }

    ListenableFuture<Void> r = t.submit();
    return Futures.transform(r, futureTrans, executor);
}