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.vtn.manager.internal.vnode.GetVlanMapFuture.java

/**
 * Construct a new instance./*w ww  . j  a  v a  2  s  . c  o  m*/
 *
 * @param ctx    MD-SAL datastore transaction context.
 * @param input  A {@link GetVlanMapInput} instance.
 * @throws RpcException
 *     The given input contains invalid value.
 */
public GetVlanMapFuture(TxContext ctx, GetVlanMapInput input) throws RpcException {
    context = ctx;

    if (input == null) {
        throw RpcUtils.getNullInputException();
    }

    // Determine the target vBridge.
    VBridgeIdentifier vbrId = VBridgeIdentifier.create(input, true);
    bridgeId = vbrId;

    // Determine the identifier for the target VLAN mapping.
    String mapId = VTNVlanMapConfig.createMapId(input);
    if (mapId == null) {
        // The specified VLAN mapping should not be present.
        setResult(null);
    } else {
        // Read the specified VLAN mapping.
        VlanMapIdentifier vmapId = new VlanMapIdentifier(vbrId, mapId);
        LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL;
        ReadTransaction rtx = ctx.getTransaction();
        Futures.addCallback(rtx.read(oper, vmapId.getIdentifier()), this);
    }
}

From source file:com.google.gerrit.server.index.change.ReindexAfterUpdate.java

@Override
public void onGitReferenceUpdated(final Event event) {
    if (event.getRefName().startsWith(RefNames.REFS_CHANGES)
            || event.getRefName().startsWith(RefNames.REFS_DRAFT_COMMENTS)
            || event.getRefName().startsWith(RefNames.REFS_USERS)) {
        return;//  ww w  .ja  v a2 s . com
    }
    Futures.addCallback(executor.submit(new GetChanges(event)), new FutureCallback<List<Change>>() {
        @Override
        public void onSuccess(List<Change> changes) {
            for (Change c : changes) {
                executor.submit(new Index(event, c.getId()));
            }
        }

        @Override
        public void onFailure(Throwable ignored) {
            // Logged by {@link GetChanges#call()}.
        }
    });
}

From source file:com.github.rinde.rinsim.experiment.LocalComputer.java

@Override
public ExperimentResults compute(Builder builder, Set<SimArgs> inputs) {
    final ImmutableList.Builder<ExperimentRunner> runnerBuilder = ImmutableList.builder();
    for (final SimArgs args : inputs) {
        runnerBuilder.add(new ExperimentRunner(args));
    }/*from w  w  w  .j a v a2s  .  co m*/

    final List<ExperimentRunner> runners = runnerBuilder.build();

    final int threads = Math.min(builder.numThreads, runners.size());
    final ListeningExecutorService executor;
    if (builder.showGui) {
        executor = MoreExecutors.newDirectExecutorService();
    } else {
        executor = MoreExecutors
                .listeningDecorator(Executors.newFixedThreadPool(threads, new LocalThreadFactory()));
    }

    final List<SimulationResult> results = Collections.synchronizedList(new ArrayList<SimulationResult>());
    final ResultCollector resultCollector = new ResultCollector(executor, results, builder.resultListeners);

    try {
        for (final ExperimentRunner r : runners) {
            checkForError(executor, resultCollector);
            final ListenableFuture<SimulationResult> f = executor.submit(r);
            Futures.addCallback(f, resultCollector);
        }
        while (results.size() < inputs.size() && !resultCollector.hasError()) {
            Thread.sleep(THREAD_SLEEP_TIME_MS);
        }
        checkForError(executor, resultCollector);
    } catch (final InterruptedException e) {
        LOGGER.trace("Interrupt, shutting down the executor.");
        executor.shutdownNow();
        LOGGER.trace("Waiting for executor to shutdown.");
        try {
            final boolean executorStopped = executor.awaitTermination(MAX_WAIT_FOR_SHUTDOWN_S,
                    TimeUnit.SECONDS);
            if (executorStopped) {
                LOGGER.trace("Executor is shutdown.");
            } else {
                LOGGER.warn("Executor did not stop, timed out after {} seconds.", MAX_WAIT_FOR_SHUTDOWN_S);
            }
        } catch (final InterruptedException e1) {
            LOGGER.warn("Waiting for executor to shutdown is interrupted.");
        }
        return ExperimentResults.create(builder, ImmutableSet.<SimulationResult>of());
    }

    checkForError(executor, resultCollector);
    executor.shutdown();

    final ExperimentResults er = ExperimentResults.create(builder, ImmutableSet.copyOf(results));
    for (final ResultListener rl : builder.resultListeners) {
        rl.doneComputing(er);
    }
    return er;
}

From source file:us.physion.ovation.ui.editor.FolderVisualizationPanel.java

private void initUI() {
    newFolderLink.addActionListener((ActionEvent e) -> {
        addFolder(getFolder(), true);/*from  ww w  . j  ava2 s.  com*/
    });

    fileWell.setDelegate(new FileWell.AbstractDelegate(Bundle.Folder_Drop_Files_To_Add_Resources()) {

        @Override
        public void filesDropped(final File[] files) {
            final ProgressHandle ph = ProgressHandleFactory.createHandle(Bundle.Adding_resources());

            ListenableFuture<OvationEntity> addResources = EventQueueUtilities.runOffEDT(() -> {
                return EntityUtilities.insertResources(getFolder(), files, Lists.newLinkedList(),
                        Lists.newLinkedList());
            }, ph);

            Futures.addCallback(addResources, new FutureCallback<OvationEntity>() {

                @Override
                public void onSuccess(final OvationEntity result) {
                    if (result != null) {
                        RevealNode.forEntity(BrowserUtilities.PROJECT_BROWSER_ID, result);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    logger.error("Unable to display added file(s)", t);
                }
            });
        }
    });

    analysisFileWell.setDelegate(new FileWell.AbstractDelegate(Bundle.Project_Drop_Files_To_Add_Analysis()) {

        @Override
        public void filesDropped(final File[] files) {

            Iterable<Resource> inputElements = showInputsDialog();
            if (inputElements == null) {
                inputElements = Lists.newArrayList();
            }

            final List<Resource> inputs = Lists.newArrayList(inputElements);

            ListenableFuture<AnalysisRecord> addRecord = EventQueueUtilities.runOffEDT(() -> {
                return addAnalysisRecord(files, inputs);
            });

            Futures.addCallback(addRecord, new FutureCallback<AnalysisRecord>() {

                @Override
                public void onSuccess(final AnalysisRecord ar) {
                    RevealNode.forEntity(BrowserUtilities.PROJECT_BROWSER_ID, ar);
                }

                @Override
                public void onFailure(Throwable t) {
                    logger.error("Unable to display AnalysisRecord", t);
                }
            });
        }
    });
}

From source file:sharding.simple.shardtests.RandShardCallable.java

@Override
public Void call() throws Exception {
    DOMDataTreeCursorAwareTransaction tx = sd.getProducer().createTransaction(false);
    DOMDataTreeWriteCursor cursor = tx.createCursor(sd.getDOMDataTreeIdentifier());
    if (cursor != null) {
        cursor.enter(new YangInstanceIdentifier.NodeIdentifier(InnerList.QNAME));
    } else/*from   www.  j  a v  a 2s .  co m*/
        LOG.error("The cursor is NULL");

    YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId = new YangInstanceIdentifier.NodeIdentifierWithPredicates(
            InnerList.QNAME, DomListBuilder.IL_NAME, (long) itemIndex);
    MapEntryNode element;

    if (testData != null)
        element = testData.get(itemIndex);
    else
        element = AbstractShardTest.createListEntry(nodeId, shardNum, itemIndex);

    writeCnt++;
    if (cursor != null) {
        cursor.write(nodeId, element);
    } else
        LOG.error("The cursor is NULL");

    if (writeCnt == opsPerTx) {
        // We have reached the limit of writes-per-transaction.
        // Submit the current outstanding transaction and create
        // a new one in its place.
        txSubmitted++;
        if (cursor != null) {
            cursor.close();
        } else
            LOG.error("The cursor is NULL");
        Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
            @Override
            public void onSuccess(final Void result) {
                txOk++;
            }

            @Override
            public void onFailure(final Throwable t1) {
                LOG.error("Transaction failed, shard {}, exception {}", shardNum, t1);
                txError++;
            }
        });

        writeCnt = 0;
        tx = sd.getProducer().createTransaction(false);
        cursor = tx.createCursor(sd.getDOMDataTreeIdentifier());
        if (cursor != null) {
            cursor.enter(new YangInstanceIdentifier.NodeIdentifier(InnerList.QNAME));
        } else
            LOG.error("The cursor is NULL");
    }
    if (cursor != null) {
        cursor.close();
    } else
        LOG.error("The cursor is NULL");

    itemIndex++;

    // Submit the last outstanding transaction even if it's empty and wait
    // for it to complete. This will flush all outstanding transactions to
    // the data store. Note that all tx submits except for the last one are
    // asynchronous.
    try {
        tx.submit().checkedGet();
    } catch (TransactionCommitFailedException e) {
        LOG.error("Last transaction submit failed, shard {}, exception {}", shardNum, e);
        txError++;
    }
    return null;
}

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

public void testReadFileAttachment() {
    counter = new CountDownLatch(1);
    final IFileAttachment attachment = createFileAttachment();
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable err) {
            reportError(err);/*from  www  .  j a  v a 2 s .  co  m*/
            counter.countDown();
        }

        public void onSuccess(Void arg0) {
            try {
                checkFileAttachmentRead(attachment);
                removeAttachment(attachment);
            } catch (Exception e) {
                reportError(e);
            }
            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testReadFileAttachment() timed out");
        }
    } catch (InterruptedException e) {
        fail("testReadFileAttachment() has been interrupted");
    }

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

From source file:com.microsoft.office365.connect.DiscoveryController.java

/**
 * Provides information about the service that corresponds to the provided
 * capability./*from  w  w w  .  ja v a2 s.c o m*/
 * @param capability A string that contains the capability of the service that
 *                   is going to be discovered.
 * @return A signal to wait on before continuing execution. The signal contains the
 * ServiceInfo object with extra information about discovered service.
 */
public SettableFuture<ServiceInfo> getServiceInfo(final String capability) {

    final SettableFuture<ServiceInfo> result = SettableFuture.create();

    // First, look in the locally cached services.
    if (mServices != null) {
        boolean serviceFound = false;
        for (ServiceInfo service : mServices) {
            if (service.getcapability().equals(capability)) {
                Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for " + capability
                        + " was found in local cached services");
                result.set(service);
                serviceFound = true;
                break;
            }
        }

        if (!serviceFound) {
            NoSuchElementException noSuchElementException = new NoSuchElementException(
                    "The " + capability + " capability was not found in the local cached services.");
            Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage());
            result.setException(noSuchElementException);
        }
    } else { // The services have not been cached yet. Go ask the discovery service.
        AuthenticationManager.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID);
        ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationManager.getInstance()
                .getDependencyResolver();

        DiscoveryClient discoveryClient = new DiscoveryClient(Constants.DISCOVERY_RESOURCE_URL,
                dependencyResolver);

        try {
            ListenableFuture<List<ServiceInfo>> future = discoveryClient.getservices().read();
            Futures.addCallback(future, new FutureCallback<List<ServiceInfo>>() {
                @Override
                public void onSuccess(final List<ServiceInfo> services) {
                    Log.i(TAG, "getServiceInfo - Services discovered\n");
                    // Save the discovered services to serve further requests from the local cache.
                    mServices = services;

                    boolean serviceFound = false;
                    for (ServiceInfo service : services) {
                        if (service.getcapability().equals(capability)) {
                            Log.i(TAG, "getServiceInfo - " + service.getserviceName() + " service for "
                                    + capability + " was found in services retrieved from discovery");
                            result.set(service);
                            serviceFound = true;
                            break;
                        }
                    }

                    if (!serviceFound) {
                        NoSuchElementException noSuchElementException = new NoSuchElementException(
                                "The " + capability + " capability was not found in the user services.");
                        Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage());
                        result.setException(noSuchElementException);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e(TAG, "getServiceInfo - " + t.getMessage());
                    result.setException(t);
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "getServiceInfo - " + e.getMessage());
            result.setException(e);
        }
    }
    return result;
}

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

/**
 * The method which writes to the registry a specific entry.
 *
 * @param input The entry to be written in the registry.
 * @see LinkRegistryEntry/*from   w  w  w  .  java  2s.  c o m*/
 */
public void writeToLinkRegistry(LinkRegistryEntry input) {
    LOG.debug("Writing to Link registry input {}.", input);
    WriteTransaction transaction = db.newWriteOnlyTransaction();
    InstanceIdentifier<LinkRegistryEntry> 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 Link registry", LOG));
}

From source file:org.opendaylight.controller.cluster.datastore.ThreePhaseCommitCohort.java

private void abort(AbortTransaction message) {
    final ListenableFuture<Void> future = cohort.abort();
    final ActorRef sender = getSender();
    final ActorRef self = getSelf();

    Futures.addCallback(future, new FutureCallback<Void>() {
        public void onSuccess(Void v) {
            sender.tell(new AbortTransactionReply().toSerializable(), self);
        }/* w w w .  ja v  a 2s  . c o  m*/

        public void onFailure(Throwable t) {
            LOG.error(t, "An exception happened during abort");
            sender.tell(new akka.actor.Status.Failure(t), self);
        }
    });
}

From source file:com.microsoft.services.sharepoint.ListClient.java

/**
 * Gets the list.//from  www.  j  av  a 2  s.  co m
 *
 * @param listName the list name
 * @return the list
 */
public ListenableFuture<SPList> getList(String listName) {
    final SettableFuture<SPList> result = SettableFuture.create();
    String getListUrl = getSiteUrl() + "_api/web/lists/GetByTitle('%s')";
    getListUrl = String.format(getListUrl, urlEncode(listName));
    ListenableFuture<JSONObject> request = executeRequestJson(getListUrl, "GET");

    Futures.addCallback(request, new FutureCallback<JSONObject>() {
        @Override
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(JSONObject json) {
            SPList list = new SPList();
            list.loadFromJson(json, true);
            result.set(list);
        }
    });

    return result;
}