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.openflowplugin.impl.services.RoleService.java

public Future<BigInteger> getGenerationIdFromDevice(Short version) throws RoleChangeException {
    final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
    LOG.info("getGenerationIdFromDevice called for device:{}", nodeId.getValue());

    // send a dummy no-change role request to get the generation-id of the switch
    final RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder();
    roleRequestInputBuilder.setRole(toOFJavaRole(OfpRole.NOCHANGE));
    roleRequestInputBuilder.setVersion(version);
    roleRequestInputBuilder.setGenerationId(BigInteger.ZERO);

    final SettableFuture<BigInteger> finalFuture = SettableFuture.create();
    ListenableFuture<RpcResult<RoleRequestOutput>> genIdListenableFuture = handleServiceCall(
            roleRequestInputBuilder);//from  ww w  .j ava 2 s .  c  o m
    Futures.addCallback(genIdListenableFuture, new FutureCallback<RpcResult<RoleRequestOutput>>() {
        @Override
        public void onSuccess(RpcResult<RoleRequestOutput> roleRequestOutputRpcResult) {
            if (roleRequestOutputRpcResult.isSuccessful()) {
                RoleRequestOutput roleRequestOutput = roleRequestOutputRpcResult.getResult();
                if (roleRequestOutput != null) {
                    LOG.debug("roleRequestOutput.getGenerationId()={}", roleRequestOutput.getGenerationId());
                    finalFuture.set(roleRequestOutput.getGenerationId());
                } else {
                    LOG.info("roleRequestOutput is null in getGenerationIdFromDevice");
                    finalFuture.setException(new RoleChangeException(
                            "Exception in getting generationId for device:" + nodeId.getValue()));
                }

            } else {
                LOG.error("getGenerationIdFromDevice RPC error "
                        + roleRequestOutputRpcResult.getErrors().iterator().next().getInfo());

            }

        }

        @Override
        public void onFailure(Throwable throwable) {
            LOG.info("onFailure - getGenerationIdFromDevice RPC error {}", throwable);
            finalFuture.setException(new ExecutionException(throwable));
        }
    });
    return finalFuture;
}

From source file:org.anhonesteffort.p25.resource.ControlChannelQualifyingResource.java

@POST
@Timed/*  www  . j a v a 2s. c  o m*/
@ManagedAsync
public void qualify(@NotNull @Valid QualifyRequest request, @Suspended AsyncResponse response) {
    ChannelRequest.Reader channelRequest = transform(request);
    ListenableFuture<SamplesSourceHandler> sourceFuture = chnlzr.createSourceFor(channelRequest);

    Futures.addCallback(sourceFuture, new SamplesSourceCallback(channelRequest, response));

    response.setTimeout(config.getChannelRequestTimeoutMs(), TimeUnit.MILLISECONDS);
    response.setTimeoutHandler(asyncResponse -> sourceFuture.cancel(true));
}

From source file:io.druid.indexing.overlord.ThreadPoolTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    final TaskToolbox toolbox = toolboxFactory.build(task);
    final ListenableFuture<TaskStatus> statusFuture = exec
            .submit(new ThreadPoolTaskRunnerCallable(task, toolbox));
    final ThreadPoolTaskRunnerWorkItem taskRunnerWorkItem = new ThreadPoolTaskRunnerWorkItem(task,
            statusFuture);/*from   w  w  w.  j  a  v a2 s  .  c om*/
    runningItems.add(taskRunnerWorkItem);
    Futures.addCallback(statusFuture, new FutureCallback<TaskStatus>() {
        @Override
        public void onSuccess(TaskStatus result) {
            runningItems.remove(taskRunnerWorkItem);
        }

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

    return statusFuture;
}

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

@Override
public OperationFuture<NodeData> getData(String path, Watcher watcher) {
    if (watcher == null) {
        return super.getData(path, null);
    }//from  ww  w. j  av  a2 s . c o  m
    final RewatchOnExpireWatcher wrappedWatcher = new RewatchOnExpireWatcher(this, ActionType.DATA, path,
            watcher);
    OperationFuture<NodeData> result = super.getData(path, wrappedWatcher);
    Futures.addCallback(result, new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            wrappedWatcher.setLastResult(result);
        }

        @Override
        public void onFailure(Throwable t) {
            // No-op
        }
    });
    return result;

}

From source file:com.microsoft.office365.snippetapp.helpers.DiscoveryController.java

/**
 * Provides information about the service that corresponds to the provided
 * capability.// www  .  j  a  v a 2  s.com
 *
 * @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.
        AuthenticationController.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID);
        ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationController
                .getInstance().getDependencyResolver();

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

        try {
            ListenableFuture<List<ServiceInfo>> future = discoveryClient.getservices()
                    .select("serviceResourceId,serviceEndpointUri,capability").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:org.opendaylight.usc.manager.UscShardServiceImpl.java

@Override
public void write(LogicalDatastoreType type, final InstanceIdentifier<DataObject> id, final DataObject data) {
    if (dataProvider == null) {
        LOG.error("Data Service is not initialized!");
        return;//from  w  w w . j ava  2s.  c o m
    }
    writeTransaction = dataProvider.newWriteOnlyTransaction();
    writeTransaction.put(type, id, data);

    Futures.addCallback(writeTransaction.submit(), new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            LOG.trace("Successfully write [{}]", data.toString());
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error(String.format("Failed to write [%s]", data.toString()), t);
        }
    });
}

From source file:org.opendaylight.netconf.topology.singleton.impl.RemoteOperationTxProcessorImpl.java

@Override
public void doSubmit(final ActorRef recipient, final ActorRef sender) {
    currentUser = null;/*  w w  w.  jav  a2 s .c o  m*/
    if (writeTx != null) {
        CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTx.submit();
        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                recipient.tell(new SubmitReply(), sender);
            }

            @Override
            public void onFailure(@Nonnull Throwable throwable) {
                recipient.tell(throwable, sender);
            }
        });
    } else {
        recipient.tell(new SubmitFailedReply(), sender);
        LOG.warn("{}: Couldn't submit transaction because it was already closed.", id);
    }
}

From source file:org.opendaylight.atrium.bgprouter.impl.DeviceListener.java

@Override
public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
    Map<InstanceIdentifier<?>, DataObject> createdData = change.getCreatedData();

    for (Map.Entry<InstanceIdentifier<?>, DataObject> entrySet : createdData.entrySet()) {

        InstanceIdentifier<?> iiD = entrySet.getKey();
        final DataObject dataObject = entrySet.getValue();

        if (dataObject instanceof FlowCapableNode) {
            final InstanceIdentifier<Node> path = iiD.firstIdentifierOf(Node.class);

            ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
            final CheckedFuture<Optional<Node>, ReadFailedException> readFuture = readOnlyTransaction
                    .read(LogicalDatastoreType.OPERATIONAL, path);
            Futures.addCallback(readFuture, new FutureCallback<Optional<Node>>() {
                @Override/*from www .ja  v  a2s.c o  m*/
                public void onSuccess(Optional<Node> result) {
                    if (result.isPresent()) {
                        bgpRouter.processNodeAdd(result.get().getId());
                        LOG.info("Node discovered and passed to processNodeAdd : " + result.get().getId());
                    } else {
                        LOG.info("Read succeeded, node doesn't exist: {}", path);
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    LOG.info("Failed to read Node: {}", path, t);
                }
            });
        }
    }
}

From source file:org.hawkular.metrics.api.jaxrs.handler.CounterHandler.java

@POST
@Path("/{group}/{counter}")
@ApiOperation(value = "Increase value of a counter", hidden = true)
public void updateCounter(@Suspended final AsyncResponse asyncResponse, @PathParam("group") String group,
        @PathParam("counter") String counter) {
    ListenableFuture<Void> future = metricsService
            .updateCounter(new Counter(DEFAULT_TENANT_ID, group, counter, 1L));
    Futures.addCallback(future, new NoDataCallback<>(asyncResponse));
}

From source file:com.microsoft.tooling.msservices.serviceexplorer.RefreshableNode.java

public ListenableFuture<List<Node>> load() {
    final RefreshableNode node = this;
    final SettableFuture<List<Node>> future = SettableFuture.create();

    DefaultLoader.getIdeHelper().runInBackground(getProject(), "Loading " + getName() + "...", false, true,
            null, new Runnable() {
                @Override// w ww  .  j a va 2s.com
                public void run() {
                    final String nodeName = node.getName();
                    node.setName(nodeName + " (Refreshing...)");

                    Futures.addCallback(future, new FutureCallback<List<Node>>() {
                        @Override
                        public void onSuccess(List<Node> nodes) {
                            updateName(null);
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            updateName(throwable);
                        }

                        private void updateName(final Throwable throwable) {
                            DefaultLoader.getIdeHelper().invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    node.setName(nodeName);

                                    if (throwable != null) {
                                        DefaultLoader.getUIHelper().showException(
                                                "An error occurred while attempting " + "to load "
                                                        + node.getName() + ".",
                                                throwable, "MS Services - Error Loading " + node.getName(),
                                                false, true);
                                    }
                                }
                            });
                        }
                    });

                    node.refreshItems(future);
                }
            });

    return future;
}