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

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

Introduction

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

Prototype

public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) 

Source Link

Document

Registers separate success and failure callbacks to be run when the Future 's computation is java.util.concurrent.Future#isDone() complete or, if the computation is already complete, immediately.

Usage

From source file:com.facebook.swift.service.async.AsyncClient.java

@Test(timeOut = 2000)
void testAsyncConnection() throws Exception {
    DelayedMap.AsyncClient client = null;
    final CountDownLatch latch = new CountDownLatch(1);

    ListenableFuture<DelayedMap.AsyncClient> future = createClient(DelayedMap.AsyncClient.class, syncServer);
    Futures.addCallback(future, new FutureCallback<DelayedMap.AsyncClient>() {
        @Override// w  w  w. ja v  a  2s. c  o m
        public void onSuccess(DelayedMap.AsyncClient client) {
            ListenableFuture<String> getBeforeFuture;
            ListenableFuture<String> getAfterFuture;
            ListenableFuture<Void> putFuture;

            try {
                try {
                    getBeforeFuture = client.getValueSlowly(200, TimeUnit.MILLISECONDS, "testKey");
                    putFuture = client.putValueSlowly(400, TimeUnit.MILLISECONDS, "testKey", "testValue");
                    getAfterFuture = client.getValueSlowly(600, TimeUnit.MILLISECONDS, "testKey");

                    assertEquals(Uninterruptibles.getUninterruptibly(getBeforeFuture), "default");
                    assertEquals(Uninterruptibles.getUninterruptibly(getAfterFuture), "testValue");
                    Uninterruptibles.getUninterruptibly(putFuture);
                } finally {
                    client.close();
                }
            } catch (Throwable t) {
                onFailure(t);
            }

            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            Throwables.propagate(t);
            latch.countDown();
        }
    });

    latch.await();
}

From source file:com.metamx.druid.merger.coordinator.ThreadPoolTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    final TaskToolbox toolbox = toolboxFactory.build(task);
    final ListenableFuture<TaskStatus> statusFuture = exec
            .submit(new ExecutorServiceTaskRunnerCallable(task, toolbox));

    final TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem(task, statusFuture, null,
            new DateTime());
    runningItems.add(taskRunnerWorkItem);
    Futures.addCallback(statusFuture, new FutureCallback<TaskStatus>() {
        @Override/*from   w  ww.j ava 2 s .c o  m*/
        public void onSuccess(TaskStatus result) {
            runningItems.remove(taskRunnerWorkItem);
        }

        @Override
        public void onFailure(Throwable t) {
            runningItems.remove(taskRunnerWorkItem);
        }
    });

    return statusFuture;
}

From source file:org.opendaylight.router.UserDataHandler.java

public void writeDataToOperationDataStore(InstanceIdentifier<SubInterface> subInterfaceIID,
        SubInterface subInterface) {/*  ww w  . ja  va2  s  . c  o  m*/
    WriteTransaction wtx = dataBroker.newWriteOnlyTransaction();
    wtx.merge(LogicalDatastoreType.OPERATIONAL, subInterfaceIID, subInterface);
    CheckedFuture<Void, TransactionCommitFailedException> future = wtx.submit();

    Futures.addCallback(future, new FutureCallback<Void>() {

        @Override
        public void onSuccess(Void result) {
            LOG.info("wrote successfully to operational data store.");
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.info("failed to write to operational datastore.");
        }
    });
}

From source file:org.apache.twill.internal.zookeeper.FailureRetryZKClient.java

@Override
public OperationFuture<String> create(final String path, @Nullable final byte[] data,
        final CreateMode createMode, final boolean createParent, final Iterable<ACL> acl) {
    // No retry for any SEQUENTIAL node, as some algorithms depends on only one sequential node being created.
    if (createMode == CreateMode.PERSISTENT_SEQUENTIAL || createMode == CreateMode.EPHEMERAL_SEQUENTIAL) {
        return super.create(path, data, createMode, createParent, acl);
    }//  w  ww.  j  av  a 2 s  . c  o m

    final SettableOperationFuture<String> result = SettableOperationFuture.create(path,
            Threads.SAME_THREAD_EXECUTOR);
    Futures.addCallback(super.create(path, data, createMode, createParent, acl),
            new OperationFutureCallback<String>(OperationType.CREATE, System.currentTimeMillis(), path, result,
                    new Supplier<OperationFuture<String>>() {
                        @Override
                        public OperationFuture<String> get() {
                            return FailureRetryZKClient.super.create(path, data, createMode, createParent, acl);
                        }
                    }));
    return result;
}

From source file:io.crate.autocomplete.AutoCompleter.java

public ListenableFuture<CompletionResult> complete(String statement) {
    StatementLexer lexer = getLexer(statement);
    final Context ctx = new Context(statement.length());
    List<ListenableFuture<List<String>>> futureCompletions;
    try {/*from  ww  w  .j  a v a2s.  c o  m*/
        futureCompletions = innerComplete(lexer, statement, ctx);
    } catch (ParsingException e) {
        return Futures.immediateFuture(new CompletionResult(0, Collections.<String>emptyList()));
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        return Futures.immediateFuture(new CompletionResult(0, Collections.<String>emptyList()));
    }

    final SettableFuture<CompletionResult> result = SettableFuture.create();
    Futures.addCallback(Futures.allAsList(futureCompletions), new FutureCallback<List<List<String>>>() {
        @Override
        public void onSuccess(@Nullable List<List<String>> completionsList) {
            if (completionsList == null) {
                result.set(new CompletionResult(0, ImmutableList.<String>of()));
                return;
            }
            if (ctx.parts.size() > 1) {
                Set<String> fullyQualifiedCompletions = new TreeSet<>();
                for (List<String> completions : completionsList) {
                    for (String completion : completions) {
                        ctx.parts.set(ctx.parts.size() - 1, completion);
                        fullyQualifiedCompletions.add(dotJoiner.join(ctx.parts));
                    }
                }
                result.set(new CompletionResult(ctx.startIdx, fullyQualifiedCompletions));
            } else {
                Set<String> uniqueSortedCompletions = new TreeSet<>();
                for (List<String> completions : completionsList) {
                    uniqueSortedCompletions.addAll(completions);
                }
                result.set(new CompletionResult(ctx.startIdx, uniqueSortedCompletions));
            }
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            result.setException(t);
        }
    });
    return result;
}

From source file:io.github.chenguangqi.toaster.impl.ToasterProvider.java

@Override
public void close() throws Exception {
    if (null != dataBroker) {
        WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
        tx.delete(LogicalDatastoreType.OPERATIONAL, TOASTER_IID);
        Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
            @Override/*from   w  ww .  j a  va  2 s  .c  o m*/
            public void onSuccess(@Nullable Void aVoid) {
                LOG.info("close: transaction succeeded");
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOG.error("close: transaction failed");
            }
        });
    }
    LOG.info("ToasterProvider Closed");
}

From source file:org.opendaylight.controller.md.statistics.manager.AbstractStatsTracker.java

protected final <T extends TransactionAware> void requestHelper(Future<RpcResult<T>> future) {
    Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future), callback);
}

From source file:com.facebook.buck.util.concurrent.JobLimiter.java

private <V> ListenableFuture<V> send(ThrowingSupplier<ListenableFuture<V>, Exception> callable) {
    ListenableFuture<V> future;//  w w w .j a  v  a 2  s.co  m
    try {
        future = callable.get();
    } catch (Throwable e) {
        future = Futures.immediateFailedFuture(e);
    }
    Futures.addCallback(future, MoreFutures.finallyCallback(this::release));
    return future;
}

From source file:com.microsoft.artcurator.net.MessagesLoader.java

/**
 * Loads an Attachment/* w w  w .ja v  a  2s .com*/
 *
 * @param client       the client to make the request
 * @param msgId        the Message hosting the Attachment
 * @param attachmentId the Attachment to load
 * @param callback     callback to notify on success/failure
 */
public static void getAttachmentAsync(OutlookClient client, String msgId, String attachmentId,
        FutureCallback<Attachment> callback) {
    ListenableFuture<Attachment> attachmentListenableFuture = client.getMe().getMessage(msgId)
            .getAttachment(attachmentId).read();
    Futures.addCallback(attachmentListenableFuture, callback);
}

From source file:eu.point.registry.impl.NodeRegistryUtils.java

/**
 * The method which writes to the registry a specific entry.
 *
 * @param input The entry to be written in the registry.
 * @see NodeRegistryEntry/*from   w  ww  .j av a2 s  .c o m*/
 */
public void writeToNodeRegistry(NodeRegistryEntry input) {
    LOG.debug("Writing to Node registry input {}.", input);
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<NodeRegistryEntry> iid = toInstanceIdentifier(input);

    transaction.put(LogicalDatastoreType.OPERATIONAL, iid, input);
    CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
    Futures.addCallback(future, new LoggingFuturesCallBack<Void>("Failed to write to Node registry", LOG));
}