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:org.opendaylight.firewall.impl.FirewallProvider.java

/**
 * Populates Intents' initial operational data into the MD-SAL operational
 * data store.//from   ww  w.j  a v  a2  s  .  c o  m
 */
protected void initIntentsOperational() {
    // Build the initial intents operational data
    Rule rules = new RuleBuilder().build();

    // Put the Intents operational data into the MD-SAL data store
    WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
    tx.put(LogicalDatastoreType.OPERATIONAL, RULE_IID, rules);

    // Perform the tx.submit asynchronously
    Futures.addCallback(tx.submit(), new FutureCallback<Void>() {

        @Override
        public void onSuccess(final Void result) {
            LOG.info("initIntentsOperational: transaction succeeded");
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("initIntentsOperational: transaction failed");
        }
    });

    LOG.info("initIntentsOperational: operational status populated: {}", rules);
}

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

/**
 * Requests Message with Attachments based on the provided folder id
 *
 * @param client   the client to make the request
 * @param folderId the folder to inspect
 * @param callback callback to notify on success/failure
 *///from w w  w.jav  a 2  s  . c  o  m
public static void getMessagesWithAttachmentsFromFolderAsync(OutlookClient client, String folderId,
        FutureCallback<List<Message>> callback) {
    ListenableFuture<List<Message>> future = client.getMe().getFolder(folderId).getMessages()
            .filter("HasAttachments eq true and IsRead eq false").top(50).read();
    Futures.addCallback(future, callback);
}

From source file:com.google.gapid.util.SelectionHandler.java

public <T> void updateSelectionFromModel(Callable<T> onBgThread, Consumer<T> onUiThread) {
    if (handlingUiSelection) {
        return;/*from  www  .  ja  v  a2  s . c  o m*/
    }

    int currentSelection = lastSelectionEventId.incrementAndGet();
    lastSelectionFuture.cancel(true);
    ListenableFuture<T> future = Scheduler.EXECUTOR.submit(onBgThread);
    lastSelectionFuture = future;

    Futures.addCallback(future, new LoggingCallback<T>(log) {
        @Override
        public void onSuccess(T result) {
            if (result != null && isCurrentSelection(currentSelection)) {
                scheduleIfNotDisposed(widget, () -> {
                    if (isCurrentSelection(currentSelection)) {
                        onUiThread.accept(result);
                    }
                });
            }
        }
    });
}

From source file:webchat.client.http.FutureAdapter.java

@Override
public ChatFuture<V> addCallback(ChatCallback<V> callback) {
    Futures.addCallback(wrappedFut, new CallbackAdapter(callback));
    return this;
}

From source file:org.gradle.internal.operations.DefaultBuildOperationQueue.java

public void waitForCompletion() throws MultipleBuildOperationFailures {
    waitingForCompletion = true;/*  w  w  w  .j  av a  2  s .c o  m*/

    CountDownLatch finished = new CountDownLatch(operations.size());
    Queue<Throwable> failures = Queues.newConcurrentLinkedQueue();

    for (ListenableFuture operation : operations) {
        Futures.addCallback(operation, new CompletionCallback(finished, failures));
    }

    try {
        finished.await();
    } catch (InterruptedException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }

    // all operations are complete, check for errors
    if (!failures.isEmpty()) {
        throw new MultipleBuildOperationFailures(getFailureMessage(failures), failures, logLocation);
    }
}

From source file:org.grouplens.lenskit.util.parallel.TaskGroupRunner.java

public synchronized void submit(Runnable task) {
    ListenableFuture<?> result = executor.submit(task);
    activeTasks.add(result);/* ww w .  j  a va 2  s  . c om*/
    Futures.addCallback(result, new Callback(result));
}

From source file:com.github.rinde.rinsim.central.rt.SolverToRealtimeAdapter.java

@Override
public void problemChanged(final GlobalStateObject snapshot) {
    checkState(scheduler.isPresent(), "Not yet initialized.");
    cancel();// w ww .j  a va2 s  .com
    currentFuture = Optional
            .of(scheduler.get().getSharedExecutor().submit(Solvers.createSolverCallable(solver, snapshot)));

    Futures.addCallback(currentFuture.get(), new FutureCallback<ImmutableList<ImmutableList<Parcel>>>() {
        @Override
        public void onSuccess(@Nullable ImmutableList<ImmutableList<Parcel>> result) {
            LOGGER.trace("onSuccess: " + result);
            if (result == null) {
                scheduler.get().reportException(new IllegalArgumentException(
                        "Solver.solve(..) must return a " + "non-null result. Solver: " + solver));
            } else {
                scheduler.get().updateSchedule(snapshot, result);
                scheduler.get().doneForNow();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof CancellationException) {
                LOGGER.trace("Solver execution got cancelled");
                return;
            }
            scheduler.get().reportException(t);
        }
    });
}

From source file:com.microsoft.office.integration.test.AttachmentsAsyncTestCase.java

public void testCreateFileAttachment() {
    final IFileAttachment attachment = createFileAttachment();
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onSuccess(Void res) {
            try {
                checkCreated(attachment);
                removeAttachment(attachment);
            } catch (Throwable e) {
                reportError(e);//from  w  ww  .j  av a2 s . co  m
            }
            counter.countDown();
        }

        public void onFailure(Throwable err) {
            reportError(err);
            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testCreateFileAttachment() timed out");
        }
    } catch (InterruptedException e) {
        fail("testCreateFileAttachment() has been interrupted");
    }

    try {
        removeMessages();
    } catch (Throwable t) {
        reportError(t);
    }
}

From source file:fr.duminy.components.swing.listpanel.JListComponentWrapper.java

@Override
public void addItem() {
    ListenableFuture<B> futureItem = itemManager.createItem();

    Futures.addCallback(futureItem, new FutureCallback<B>() {
        @Override//from   ww w .j  a v  a2 s .c  o m
        public void onSuccess(B result) {
            model.add(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof CancellationException) {
                LOG.info("the user has cancelled the addition of an item");
            } else {
                //TODO give a user feedback
                LOG.error("Can't add an item", t);
            }
        }
    });
}

From source file:org.opendaylight.netconf.topology.impl.OnlySuccessStateAggregator.java

@Override
public ListenableFuture<Node> combineUpdateAttempts(List<ListenableFuture<Node>> stateFutures) {
    final SettableFuture<Node> future = SettableFuture.create();
    final ListenableFuture<List<Node>> allAsList = Futures.allAsList(stateFutures);
    Futures.addCallback(allAsList, new FutureCallback<List<Node>>() {
        @Override//from w ww.j a  va2s .c  o  m
        public void onSuccess(List<Node> result) {
            for (int i = 0; i < result.size() - 1; i++) {
                if (!result.get(i).equals(result.get(i + 1))) {
                    future.setException(new IllegalStateException("Update futures have different result"));
                }
            }
            future.set(result.get(0));
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error("One of the combined update attempts failed {}", t);
            future.setException(t);
        }
    });
    return future;
}