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.controller.cluster.datastore.LocalTransactionContext.java

@Override
public <T> void executeRead(AbstractRead<T> readCmd, final SettableFuture<T> proxyFuture) {
    Futures.addCallback(readCmd.apply(getReadDelegate()), new FutureCallback<T>() {
        @Override//  w ww . jav  a2s . co m
        public void onSuccess(final T result) {
            proxyFuture.set(result);
        }

        @Override
        public void onFailure(final Throwable t) {
            proxyFuture.setException(t);
        }
    });
}

From source file:io.crate.executor.transport.distributed.DownstreamOperationContext.java

public DownstreamOperationContext(DownstreamOperation downstreamOperation,
        final SettableFuture<Object[][]> listener, Streamer<?>[] streamers,
        DistributedRequestContextManager.DoneCallback doneCallback) {
    this.mergeOperationsLeft = new AtomicInteger(downstreamOperation.numUpstreams());
    this.downstreamOperation = downstreamOperation;
    this.listener = listener;
    Futures.addCallback(downstreamOperation.result(), new FutureCallback<Object[][]>() {
        @Override//ww w  .  j  a  va2  s. co  m
        public void onSuccess(@Nullable Object[][] result) {
            listener.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            listener.setException(t);

        }
    });
    this.streamers = streamers;
    this.doneCallback = doneCallback;
}

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

/**
 * Gets lists./*from w w  w.j  a va  2s. c om*/
 *
 * @param query the query
 * @return the lists
 */
public ListenableFuture<List<SPList>> getLists(Query query) {
    final SettableFuture<List<SPList>> result = SettableFuture.create();

    String queryOData = generateODataQueryString(query);
    String getListsUrl = getSiteUrl() + "_api/web/lists/?" + queryEncode(queryOData);

    ListenableFuture<JSONObject> request = executeRequestJson(getListsUrl, "GET");

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

        @Override
        public void onSuccess(JSONObject json) {
            try {
                List<SPList> list = SPList.listFromJson(json);
                result.set(list);
            } catch (JSONException e) {
                log(e);
            }
        }
    });

    return result;
}

From source file:org.opendaylight.mdsal.dom.broker.TransactionChainWriteTransaction.java

@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit() {
    final CheckedFuture<Void, TransactionCommitFailedException> writeResultFuture = delegateTx.submit();
    Futures.addCallback(writeResultFuture, new FutureCallback<Void>() {
        @Override/*www  .jav  a 2s . c om*/
        public void onSuccess(@Nullable final Void result) {
            // NOOP
        }

        @Override
        public void onFailure(final Throwable throwable) {
            txChain.transactionFailed(TransactionChainWriteTransaction.this, throwable);
        }
    });

    txChain.closeWriteTransaction(writeResultFuture);
    return writeResultFuture;
}

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

public void testNavigationProperty() {
    // succeeded if no exception generated
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.getDraftsAsync(), new FutureCallback<IFolder>() {
        public void onFailure(Throwable t) {
            reportError(t);//from w w  w . j av  a 2s. c om
            counter.countDown();
        }

        public void onSuccess(IFolder drafts) {
            try {
                final CountDownLatch cdl = new CountDownLatch(1);
                Futures.addCallback(drafts.getMessagesAsync(), new FutureCallback<IMessages>() {
                    public void onFailure(Throwable t) {
                        reportError(t);
                        cdl.countDown();
                    }

                    public void onSuccess(IMessages result) {
                        try {
                            result.getAllAsync().get();
                        } catch (Throwable t) {
                            reportError(t);
                        }

                        cdl.countDown();
                    }
                });
                cdl.await();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });
    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testSize() timed out");
        }
    } catch (InterruptedException e) {
        fail("testSize() has been interrupted");
    }
}

From source file:org.opendaylight.bgpcep.pcep.topology.spi.AbstractInstructionExecutor.java

public static FailureCase schedule(final InstructionScheduler scheduler,
        final AbstractInstructionExecutor fwd) {
    final ListenableFuture<Instruction> s;
    try {//w w w . ja v  a 2  s . com
        s = scheduler.scheduleInstruction(fwd.getInput());
    } catch (final SchedulerException e) {
        LOG.info("Instuction {} failed to schedule", e.getMessage(), e);
        return new FailureCaseBuilder().setFailure(e.getFailure()).build();
    }
    Futures.addCallback(s, fwd);
    return null;
}

From source file:io.crate.jobs.NestedLoopContext.java

public NestedLoopContext(ESLogger logger, NestedLoopPhase nestedLoopPhase,
        NestedLoopOperation nestedLoopOperation, @Nullable PageBucketReceiver leftBucketReceiver,
        @Nullable PageBucketReceiver rightBucketReceiver) {
    super(nestedLoopPhase.phaseId(), logger);

    this.nestedLoopPhase = nestedLoopPhase;
    this.leftBucketReceiver = leftBucketReceiver;
    this.rightBucketReceiver = rightBucketReceiver;

    leftRowReceiver = nestedLoopOperation.leftRowReceiver();
    rightRowReceiver = nestedLoopOperation.rightRowReceiver();

    Futures.addCallback(nestedLoopOperation.completionFuture(), new FutureCallback<Object>() {
        @Override/* www  .  ja  v  a2 s . co m*/
        public void onSuccess(@Nullable Object result) {
            future.close(null);
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            future.close(t);
        }
    });
}

From source file:com.boundlessgeo.suite.geoserver.cloudwatch.aws.CloudwatchSender.java

/**
 * Invoked by spring on a timer to get and send from all metric providers
 *///from   w  w  w  .j ava 2  s .  c o m
public void sendAllMetrics() {
    if (!enabled) {
        logger.debug("Metrics are disabled...returning");
        return;
    }
    logger.debug("Sending all metrics");
    for (MetricProvider mp : providers) {
        if (!mp.getEnabled())
            continue;
        for (final MetricDatum md : mp.getMetrics()) {
            try {
                PutMetricDataRequest request = new PutMetricDataRequest().withNamespace("geoserver")
                        .withMetricData(md);
                logger.trace("Sending statistic {}", md.getMetricName());
                ListenableFuture<java.lang.Void> f = JdkFutureAdapters
                        .listenInPoolThread(cloudwatch.putMetricDataAsync(request));
                Futures.addCallback(f, new FutureCallback<java.lang.Void>() {
                    public void onSuccess(java.lang.Void ignored) {
                        logger.trace("Sent statistic {}", md.getMetricName());
                    }

                    public void onFailure(Throwable ex) {
                        logger.error("Error sending metric: {}", md.getMetricName(), ex);
                    }
                });
            } catch (AmazonClientException ex) {
                logger.warn("Error sending AWS metric {}", md.getMetricName());
            }
        }
    }
}

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

@Override
public ListenableFuture<Node> combineCreateAttempts(final 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   ww w.j  ava 2 s. c  o  m*/
        public void onSuccess(final List<Node> result) {
            Node base = null;
            NetconfNode baseAugmentation = null;
            AvailableCapabilities masterCaps = null;
            UnavailableCapabilities unavailableMasterCaps = null;
            final ArrayList<NodeStatus> statusList = new ArrayList<>();
            for (final Node node : result) {
                final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
                if (base == null && netconfNode.getConnectionStatus().equals(ConnectionStatus.Connected)) {
                    base = node;
                    baseAugmentation = netconfNode;
                }
                // we need to pull out caps from master, since slave does not go through resolution
                if (masterCaps == null) {
                    masterCaps = netconfNode.getAvailableCapabilities();
                    unavailableMasterCaps = netconfNode.getUnavailableCapabilities();
                }
                if (netconfNode.getAvailableCapabilities().getAvailableCapability().size() > masterCaps
                        .getAvailableCapability().size()) {
                    masterCaps = netconfNode.getAvailableCapabilities();
                    unavailableMasterCaps = netconfNode.getUnavailableCapabilities();
                }
                LOG.debug(netconfNode.toString());
                statusList.addAll(netconfNode.getClusteredConnectionStatus().getNodeStatus());
            }

            if (base == null) {
                base = result.get(0);
                baseAugmentation = result.get(0).getAugmentation(NetconfNode.class);
                LOG.debug("All results {}", result.toString());
            }

            final Node aggregatedNode = new NodeBuilder(base).addAugmentation(NetconfNode.class,
                    new NetconfNodeBuilder(baseAugmentation)
                            .setClusteredConnectionStatus(
                                    new ClusteredConnectionStatusBuilder().setNodeStatus(statusList).build())
                            .setAvailableCapabilities(masterCaps)
                            .setUnavailableCapabilities(unavailableMasterCaps).build())
                    .build();

            future.set(aggregatedNode);
        }

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

From source file:com.magnet.yak.command.RegisterUserCmd.java

public ListenableFuture<RegisterUserCmdOutput> execAsync(final RegisterUserCmdInput input) {
    LOGGER.trace("apply : input={}", input);
    setup(input);/*w  w  w.j  a va  2  s.co  m*/
    final SettableFuture<RegisterUserCmdOutput> future = SettableFuture.create();
    final SettableFuture<Void> onAuth = SettableFuture.create();
    final MMXMessageListener messageListener = new MMXMessageListenerImpl(input.getUsername(), mmxClient);
    final MMXConnectionListener connectionListener = new MMXConnectionListenerImpl(input.getUsername(), onAuth);

    Futures.addCallback(onAuth, new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            LOGGER.trace("onFailure : input={}", input, t);
            future.setException(t);
        }

        public void onSuccess(Void v) {
            LOGGER.trace("onSuccess : input={}", input);
            future.set(new RegisterUserCmdOutput(mmxClient, input.getUsername(), input.getPassword(),
                    connectionListener, messageListener));
        }
    });

    ExecUtil.getService().submit(new Runnable() {
        public void run() {
            try {
                Log.setLoggable("test", 6);
                mmxClient.connect(input.getUsername(), input.getPassword().getBytes(), connectionListener,
                        messageListener, false);
            } catch (MMXException e) {
                e.printStackTrace();
            }
        }
    });

    return future;
}