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.dao.entity.BaseEntityService.java

@Override
public ListenableFuture<String> fetchEntityNameAsync(TenantId tenantId, EntityId entityId) {
    log.trace("Executing fetchEntityNameAsync [{}]", entityId);
    ListenableFuture<String> entityName;
    ListenableFuture<? extends HasName> hasName;
    switch (entityId.getEntityType()) {
    case ASSET:/*from  www .  jav  a 2 s  .c o  m*/
        hasName = assetService.findAssetByIdAsync(tenantId, new AssetId(entityId.getId()));
        break;
    case DEVICE:
        hasName = deviceService.findDeviceByIdAsync(tenantId, new DeviceId(entityId.getId()));
        break;
    case ENTITY_VIEW:
        hasName = entityViewService.findEntityViewByIdAsync(tenantId, new EntityViewId(entityId.getId()));
        break;
    case TENANT:
        hasName = tenantService.findTenantByIdAsync(tenantId, new TenantId(entityId.getId()));
        break;
    case CUSTOMER:
        hasName = customerService.findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId()));
        break;
    case USER:
        hasName = userService.findUserByIdAsync(tenantId, new UserId(entityId.getId()));
        break;
    case DASHBOARD:
        hasName = dashboardService.findDashboardInfoByIdAsync(tenantId, new DashboardId(entityId.getId()));
        break;
    case ALARM:
        hasName = alarmService.findAlarmByIdAsync(tenantId, new AlarmId(entityId.getId()));
        break;
    case RULE_CHAIN:
        hasName = ruleChainService.findRuleChainByIdAsync(tenantId, new RuleChainId(entityId.getId()));
        break;
    default:
        throw new IllegalStateException("Not Implemented!");
    }
    entityName = Futures.transform(hasName,
            (Function<HasName, String>) hasName1 -> hasName1 != null ? hasName1.getName() : null);
    return entityName;
}

From source file:net.oneandone.troilus.MutationQuery.java

protected ListenableFuture<ImmutableSet<Statement>> transformBatchablesToStatement(final DBSession dbSession,
        ListenableFuture<ImmutableSet<? extends Batchable<?>>> batchablesFutureSet) {

    Function<ImmutableSet<? extends Batchable<?>>, ImmutableSet<ListenableFuture<Statement>>> batchablesToStatement = new Function<ImmutableSet<? extends Batchable<?>>, ImmutableSet<ListenableFuture<Statement>>>() {
        @Override/*w  w  w .j  a  v a  2 s.  co m*/
        public ImmutableSet<ListenableFuture<Statement>> apply(
                ImmutableSet<? extends Batchable<?>> batchables) {
            Set<ListenableFuture<Statement>> statementFutureSet = Sets.newHashSet();
            for (Batchable<?> batchable : batchables) {
                statementFutureSet.add(batchable.getStatementAsync(dbSession));
            }
            return ImmutableSet.copyOf(statementFutureSet);
        }
    };
    ListenableFuture<ImmutableSet<ListenableFuture<Statement>>> statementFutureSet = Futures
            .transform(batchablesFutureSet, batchablesToStatement);
    return ListenableFutures.flat(statementFutureSet, getExecutor());
}

From source file:org.opendaylight.bgpcep.pcep.tunnel.provider.DestroyTunnelInstructionExecutor.java

@Override
protected ListenableFuture<OperationResult> invokeOperation() {
    final InstanceIdentifier<Topology> tii = TopologyProgrammingUtil
            .topologyForInput(this.pcepDestroyTunnelInput);
    final InstanceIdentifier<Link> lii = TunnelProgrammingUtil.linkIdentifier(tii, this.pcepDestroyTunnelInput);
    try (final ReadOnlyTransaction t = this.dataProvider.newReadOnlyTransaction()) {
        final Node node;
        final Link link;
        try {/*from w w w.jav  a 2s  . c  o m*/
            // The link has to exist
            link = t.read(LogicalDatastoreType.OPERATIONAL, lii).checkedGet().get();
            // The source node has to exist
            node = TunelProgrammingUtil.sourceNode(t, tii, link).get();
        } catch (IllegalStateException | ReadFailedException e) {
            LOG.debug("Link or node does not exist.", e);
            return TunelProgrammingUtil.RESULT;
        }
        final RemoveLspInputBuilder ab = new RemoveLspInputBuilder();
        ab.setName(link.getAugmentation(Link1.class).getSymbolicPathName());
        ab.setNode(node.getSupportingNode().get(0).getKey().getNodeRef());
        return Futures.transform(
                (ListenableFuture<RpcResult<RemoveLspOutput>>) this.topologyService.removeLsp(ab.build()),
                new Function<RpcResult<RemoveLspOutput>, OperationResult>() {
                    @Override
                    public OperationResult apply(final RpcResult<RemoveLspOutput> input) {
                        return input.getResult();
                    }
                });
    }
}

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

private CheckedFuture<DOMRpcResult, DOMRpcException> transformResult(final SchemaPath schemaPath,
        final ListenableFuture<RpcResult<?>> bindingResult) {
    final ListenableFuture<DOMRpcResult> transformed = Futures.transform(bindingResult, lazySerializedMapper);
    return Futures.makeChecked(transformed, EXCEPTION_MAPPER);
}

From source file:org.opendaylight.controller.sal.connect.netconf.sal.tx.WriteRunningTx.java

@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
            new Function<RpcResult<TransactionStatus>, Void>() {
                @Override//from   ww w .j  av  a2  s.  c  o m
                public Void apply(final RpcResult<TransactionStatus> input) {
                    return null;
                }
            });

    return Futures.makeChecked(commmitFutureAsVoid,
            new Function<Exception, TransactionCommitFailedException>() {
                @Override
                public TransactionCommitFailedException apply(final Exception input) {
                    return new TransactionCommitFailedException(
                            "Submit of transaction " + getIdentifier() + " failed", input);
                }
            });
}

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

@Override
protected ListenableFuture<Node> doLoad(Path.Any path) {
    return Futures.transformAsync(client.get(path),
            tree -> Futures.transform(client.get(Paths.toAny(tree.getCommandTree().getRoot())),
                    val -> new RootNode(tree.getCommandTree().getRoot().getTree(), val.getCommandTreeNode())));
}

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

public ListenableFuture<ImageData> getThumbnail(long atomId, int size) {
    Thumbnail result = new Thumbnail(atomId, getPath(atomId));
    synchronized (queuedThumbnails) {
        queuedThumbnails.add(result);/*  w  w  w .  ja  va 2s.c  o m*/
        queuedThumbnails.notify();
    }
    return Futures.transform(result.result, image -> processImage(image, size));
}

From source file:io.druid.indexing.worker.executor.ExecutorLifecycle.java

@LifecycleStart
public void start() {
    final File taskFile = Preconditions.checkNotNull(config.getTaskFile(), "taskFile");
    final File statusFile = Preconditions.checkNotNull(config.getStatusFile(), "statusFile");
    final InputStream parentStream = Preconditions.checkNotNull(config.getParentStream(), "parentStream");

    final Task task;

    try {/*from  w ww. j  a  v a 2  s  .c  o  m*/
        task = jsonMapper.readValue(taskFile, Task.class);

        log.info("Running with task: %s", jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(task));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // Spawn monitor thread to keep a watch on parent's stdin
    // If stdin reaches eof, the parent is gone, and we should shut down
    parentMonitorExec.submit(new Runnable() {
        @Override
        public void run() {
            try {
                while (parentStream.read() != -1) {
                    // Toss the byte
                }
            } catch (Exception e) {
                log.error(e, "Failed to read from stdin");
            }

            // Kind of gross, but best way to kill the JVM as far as I know
            log.info("Triggering JVM shutdown.");
            System.exit(2);
        }
    });

    // Won't hurt in remote mode, and is required for setting up locks in local mode:
    try {
        if (!task.isReady(taskActionClientFactory.create(task))) {
            throw new ISE("Task is not ready to run yet!", task.getId());
        }
    } catch (Exception e) {
        throw new ISE(e, "Failed to run isReady", task.getId());
    }

    statusFuture = Futures.transform(taskRunner.run(task), new Function<TaskStatus, TaskStatus>() {
        @Override
        public TaskStatus apply(TaskStatus taskStatus) {
            try {
                log.info("Task completed with status: %s",
                        jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(taskStatus));

                final File statusFileParent = statusFile.getParentFile();
                if (statusFileParent != null) {
                    statusFileParent.mkdirs();
                }
                jsonMapper.writeValue(statusFile, taskStatus);

                return taskStatus;
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    });
}

From source file:org.thingsboard.server.dao.AbstractModelDao.java

protected ListenableFuture<T> findOneByStatementAsync(Statement statement) {
    if (statement != null) {
        statement.setConsistencyLevel(cluster.getDefaultReadConsistencyLevel());
        ResultSetFuture resultSetFuture = getSession().executeAsync(statement);
        ListenableFuture<T> result = Futures.transform(resultSetFuture, new Function<ResultSet, T>() {
            @Nullable/*  ww  w .  j a va  2 s.  co  m*/
            @Override
            public T apply(@Nullable ResultSet resultSet) {
                Result<T> result = getMapper().map(resultSet);
                if (result != null) {
                    return result.one();
                } else {
                    return null;
                }
            }
        });
        return result;
    }
    return Futures.immediateFuture(null);
}

From source file:io.v.v23.syncbase.nosql.DatabaseImpl.java

@Override
public ListenableFuture<Map<String, Permissions>> getPermissions(VContext ctx) {
    return Futures.transform(client.getPermissions(ctx),
            new Function<ObjectClient.GetPermissionsOut, Map<String, Permissions>>() {
                @Override/*  w  w w  .  j a va2  s.c o  m*/
                public Map<String, Permissions> apply(ObjectClient.GetPermissionsOut perms) {
                    return ImmutableMap.of(perms.version, perms.perms);
                }
            });
}