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:com.spotify.asyncdatastoreclient.example.ExampleAsync.java

public static void main(final String... args) throws Exception {
    final DatastoreConfig config = DatastoreConfig.builder().connectTimeout(5000).requestTimeout(1000)
            .maxConnections(5).requestRetry(3).dataset("my-dataset").namespace("my-namespace")
            .credential(DatastoreHelper.getComputeEngineCredential()).build();

    final Datastore datastore = Datastore.create(config);

    // Add a two entities asynchronously
    final ListenableFuture<MutationResult> addFirst = addData(datastore);
    final ListenableFuture<MutationResult> addSecond = addDataInTransaction(datastore);
    final ListenableFuture<List<Object>> addBoth = Futures.allAsList(addFirst, addSecond);

    // Query the entities we've just inserted
    final ListenableFuture<QueryResult> query = Futures.transform(addBoth, (List<Object> result) -> {
        return queryData(datastore);
    });/*  w  w w .j a  v  a 2 s . c  o  m*/

    // Print the query results before clean up
    final ListenableFuture<MutationResult> delete = Futures.transform(query, (QueryResult result) -> {
        for (final Entity entity : result) {
            System.out.println("Employee name: " + entity.getString("fullname"));
            System.out.println("Employee age: " + entity.getInteger("age"));
        }
        return deleteData(datastore);
    });

    Futures.addCallback(delete, new FutureCallback<MutationResult>() {
        @Override
        public void onSuccess(final MutationResult result) {
            System.out.println("All complete.");
        }

        @Override
        public void onFailure(final Throwable throwable) {
            System.err.println("Storage exception: " + Throwables.getRootCause(throwable).getMessage());
        }
    });
}

From source file:com.vsct.strowgr.monitoring.gui.cassandra.CassandraClient.java

public static void main(String[] args) throws ExecutionException, InterruptedException {

    String node = System.getenv("cassandra.node");
    String keyspace = System.getenv("cassandra.keyspace");
    String entrypoint = System.getenv("entrypoint");
    String date = System.getenv("date");
    String since = System.getenv("since");
    showPayload = Boolean.valueOf(System.getenv("showPayload"));

    Date sinceDate = null;/*from   w w w . ja v  a2  s  .co  m*/
    if (since != null && since.contains("s"))
        sinceDate = Date.from(LocalDateTime.now().minusSeconds(Long.valueOf(since.replace("s", "")))
                .atZone(ZoneId.systemDefault()).toInstant());
    if (since != null && since.contains("m"))
        sinceDate = Date.from(LocalDateTime.now().minusMinutes(Long.valueOf(since.replace("m", "")))
                .atZone(ZoneId.systemDefault()).toInstant());
    if (since != null && since.contains("h"))
        sinceDate = Date.from(LocalDateTime.now().minusHours(Long.valueOf(since.replace("h", "")))
                .atZone(ZoneId.systemDefault()).toInstant());

    if (node == null | keyspace == null | entrypoint == null | date == null | since == null
            | showPayload == null | sinceDate == null) {
        System.out.println("You must provide these environment variables :");
        System.out.println("\t- cassandra.node");
        System.out.println("\t- cassandra.keyspace");
        System.out.println("\t- entrypoint (ex. PAO/REL1)");
        System.out.println("\t- date (ex. 2016-04-28)");
        System.out.println("\t- since (ex. 10s|25m|2h)");
        System.out.println("\t- showPayload (true or false)");
        return;
    }

    System.out.println("Initiating connection with Cassandra on " + node);

    Cluster cluster = Cluster.builder().addContactPoint(node)
            .withQueryOptions(new QueryOptions().setFetchSize(500)).build();

    Session session = cluster.connect(keyspace);

    String query;
    if (showPayload) {
        query = "select event_timestamp,event_name,correlation_id,payload from entrypoint_by_day where id='"
                + entrypoint + "' and date='" + date + "' and event_timestamp > " + sinceDate.getTime() + ";";
    } else {
        query = "select event_timestamp,event_name,correlation_id from entrypoint_by_day where id='"
                + entrypoint + "' and date='" + date + "' and event_timestamp > " + sinceDate.getTime() + ";";
    }

    System.out.println("Cassandra query=" + query + "\n");

    Statement statement = new SimpleStatement(query);

    ResultSetFuture resultSetFuture = session.executeAsync(statement);
    ListenableFuture<Multimap<Key, Value>> futur = Futures.transform(resultSetFuture, iterate(result));

    futur.get().keySet().forEach(k -> {
        System.out.print(k.correlationId + " END");
        result.get(k).forEach(v -> {
            if (showPayload) {
                System.out.print(" <- " + v.name + "(" + v.timestamp + ")|" + v.payload + "|");
            } else {
                System.out.print(" <- " + v.name + "(" + v.timestamp + ")");
            }
        });
        System.out.println(" <- BEGIN");
    });

    System.out.println("\nClosing Cassandra connection");
    session.close();
    cluster.close();
}

From source file:org.opendaylight.ovsdb.lib.impl.FutureTransformUtils.java

public static final ListenableFuture<List<OperationResult>> transformTransactResponse(
        ListenableFuture<List<JsonNode>> transactResponseFuture, final List<Operation> operations) {
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return Futures.transform(transactResponseFuture, new Function<List<JsonNode>, List<OperationResult>>() {
        @Override/*  ww  w.  j  a v  a  2 s  . co  m*/
        public List<OperationResult> apply(List<JsonNode> jsonNodes) {
            final List<OperationResult> operationResults = new ArrayList<>();
            for (int index = 0; index < jsonNodes.size(); index++) {
                JsonNode jsonNode = jsonNodes.get(index);
                OperationResult or;
                if (jsonNode != null && jsonNode.size() > 0) {
                    /*
                     * As per RFC 7047, section 4.1.3 :
                     * "In general, "result" contains some number of successful results,
                     * possibly followed by an error, in turn followed by enough JSON null
                     * values to match the number of elements in "params".  There is one
                     * exception: if all of the operations succeed, but the results cannot
                     * be committed, then "result" will have one more element than "params",
                     * with the additional element being an <error>."
                     *
                     * Hence, it is possible for a transaction response to contain more
                     * json elements than the transaction operation request.
                     * Also handle that case by checking for i < operations.size().
                     */
                    if (index < operations.size()) {
                        Operation op = operations.get(index);
                        switch (op.getOp()) {
                        case "select":
                            or = new OperationResult();
                            or.setRows(op.getTableSchema().createRows(jsonNode));
                            break;

                        default:
                            or = objectMapper.convertValue(jsonNode, OperationResult.class);

                            break;
                        }
                    } else {
                        or = objectMapper.convertValue(jsonNode, OperationResult.class);
                    }
                } else {
                    or = new OperationResult();
                }
                operationResults.add(or);
            }

            return operationResults;
        }
    });
}

From source file:io.v.impl.google.rpc.ServerRPCHelper.java

static ListenableFuture<byte[][]> prepare(Invoker invoker, VContext ctx, String method) {
    return Futures.transform(invoker.getMethodTags(ctx, method), new AsyncFunction<VdlValue[], byte[][]>() {
        @Override//ww  w  . j  a  v a2s .com
        public ListenableFuture<byte[][]> apply(VdlValue[] tags) throws Exception {
            byte[][] vomTags = new byte[tags.length][];
            for (int i = 0; i < tags.length; ++i) {
                vomTags[i] = VomUtil.encode(tags[i], tags[i].vdlType());
            }
            return Futures.immediateFuture(vomTags);
        }
    });
}

From source file:org.opendaylight.controller.md.sal.common.impl.service.AbstractDataTransaction.java

public static ListenableFuture<RpcResult<TransactionStatus>> convertToLegacyCommitFuture(
        final CheckedFuture<Void, TransactionCommitFailedException> from) {
    return Futures.transform(from, new AsyncFunction<Void, RpcResult<TransactionStatus>>() {
        @Override//from w w w  . ja v a 2s  .c  om
        public ListenableFuture<RpcResult<TransactionStatus>> apply(final Void input) {
            return SUCCESS_FUTURE;
        }
    });
}

From source file:io.v.android.apps.namespace_browser.Methods.java

static ListenableFuture<List<String>> get(VContext ctx, String name) {
    Client client = V.getClient(ctx);//from w  ww. j a  va  2s.  c o m
    VContext ctxT = ctx.withTimeout(new Duration(20000)); // 20s
    ListenableFuture<ClientCall> callFuture = client.startCall(ctxT, name, "__Signature", new Object[0],
            new Type[0]);
    final Type[] resultTypes = new Type[] { new TypeToken<Interface[]>() {
    }.getType() };
    ListenableFuture<Interface[]> sign = Futures.transform(callFuture,
            new AsyncFunction<ClientCall, Interface[]>() {
                @Override
                public ListenableFuture<Interface[]> apply(ClientCall call) throws Exception {
                    return Futures.transform(call.finish(resultTypes), new Function<Object[], Interface[]>() {
                        @Override
                        public Interface[] apply(Object[] input) {
                            return (Interface[]) (input[0]);
                        }
                    });
                }
            });
    return Futures.transform(sign, new Function<Interface[], List<String>>() {
        @Override
        public List<String> apply(Interface[] input) {
            List<String> ret = new ArrayList<String>();
            for (Interface iface : input) {
                if (iface.getMethods() != null) {
                    for (Method method : iface.getMethods()) {
                        ret.add(method.getName());
                    }
                }
            }
            return ret;
        }
    });
}

From source file:io.v.v23.syncbase.Batch.java

/**
 * Runs the given batch operation, managing retries and
 * {@link BatchDatabase#commit commit()}/{@link BatchDatabase#abort abort()}s.
 * <p>// w  w  w  . j a  v  a 2  s . co  m
 * The returned future is guaranteed to be executed on an {@link java.util.concurrent.Executor}
 * specified in {@code context} (see {@link io.v.v23.V#withExecutor}).
 * <p>
 * The returned future will fail with {@link java.util.concurrent.CancellationException} if
 * {@code context} gets canceled.
 *
 * @param context Vanadium context
 * @param db      database on which the batch operation is to be performed
 * @param opts    batch configuration
 * @param op      batch operation
 */
@CheckReturnValue
public static ListenableFuture<Void> runInBatch(VContext context, Database db, BatchOptions opts,
        BatchOperation op) {
    return VFutures.withUserLandChecks(context,
            Futures.transform(Futures.immediateFuture(false), getRetryFn(context, db, opts, op, 0)));
}

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

/**
 * Runs the given batch operation, managing retries and
 * {@link BatchDatabase#commit commit()}/{@link BatchDatabase#abort abort()}s.
 *
 * @param  ctx        Vanadium context/*from   w w  w. j  a v  a 2 s  . c  o m*/
 * @param  db         database on which the batch operation is to be performed
 * @param  opts       batch configuration
 * @param  op         batch operation
 */
public static ListenableFuture<Void> runInBatch(VContext ctx, Database db, BatchOptions opts,
        BatchOperation op) {
    return Futures.transform(Futures.immediateFuture(false), getRetryFn(ctx, db, opts, op, 0));
}

From source file:de.dfki.kiara.impl.AsyncCall.java

public static ListenableFuture<Message> performRemoteAsyncCall(final MessageConnection messageConnection,
        final Message request, ListeningExecutorService executor) {
    final ListenableFuture<Message> result = messageConnection.receive(request.getMessageId());
    final ListenableFuture<Void> reqSent = messageConnection.send(request);

    AsyncFunction<Void, Message> f = new AsyncFunction<Void, Message>() {

        @Override//from www  . ja  va 2  s  . c o m
        public ListenableFuture<Message> apply(Void input) throws Exception {
            return result;
        }
    };
    return Futures.transform(reqSent, f);
}

From source file:com.continuuity.weave.internal.ZKMessages.java

/**
 * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node.
 *
 * @param zkClient The ZooKeeper client for interacting with ZooKeeper.
 * @param messagePathPrefix ZooKeeper path prefix for the message node.
 * @param message The {@link Message} object for the content of the message node.
 * @param completionResult Object to set to the result future when the message is processed.
 * @param <V> Type of the completion result.
 * @return A {@link ListenableFuture} that will be completed when the message is consumed, which indicated
 *         by deletion of the node. If there is exception during the process, it will be reflected
 *         to the future returned./* ww w .ja  v  a  2 s  . c  o  m*/
 */
public static <V> ListenableFuture<V> sendMessage(final ZKClient zkClient, String messagePathPrefix,
        final Message message, final V completionResult) {
    return Futures.transform(
            zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL),
            new AsyncFunction<String, V>() {
                @Override
                public ListenableFuture<V> apply(String path) throws Exception {
                    return Futures.transform(ZKOperations.watchDeleted(zkClient, path),
                            new Function<String, V>() {
                                @Override
                                public V apply(String path) {
                                    return completionResult;
                                }
                            });
                }
            });
}