Example usage for com.google.common.util.concurrent SettableFuture set

List of usage examples for com.google.common.util.concurrent SettableFuture set

Introduction

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

Prototype

@Override
    public boolean set(@Nullable V value) 

Source Link

Usage

From source file:com.eviware.loadui.ui.fx.util.test.FXTestUtils.java

/**
 * Runs the given Callable in the JavaFX thread, waiting for it to complete
 * before returning. Also attempts to wait for any other JavaFX events that
 * may have been queued in the Callable to complete. If any Exception is
 * thrown during execution of the Callable, that exception will be re-thrown
 * from invokeAndWait./*from  www . j  av  a 2 s .  com*/
 * 
 * @param task
 * @param timeoutInSeconds
 * @throws Throwable
 */
public static void invokeAndWait(final Callable<?> task, int timeoutInSeconds) throws Exception {
    final SettableFuture<Void> future = SettableFuture.create();

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                task.call();
                future.set(null);
            } catch (Throwable e) {
                future.setException(e);
            }
        }
    });

    try {
        future.get(timeoutInSeconds, TimeUnit.SECONDS);
        awaitEvents();
    } catch (ExecutionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw e;
        }
    }
}

From source file:org.glowroot.central.util.MoreFutures.java

public static <V> ListenableFuture<V> onSuccessAndFailure(ListenableFuture<V> future, Runnable onSuccess,
        Runnable onFailure) {//from  ww  w . j  a v a 2s .  c om
    SettableFuture<V> outerFuture = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override
        public void onSuccess(V result) {
            onSuccess.run();
            outerFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            logger.debug(t.getMessage(), t);
            onFailure.run();
            outerFuture.setException(t);
        }
    }, MoreExecutors.directExecutor());
    return outerFuture;
}

From source file:com.continuuity.weave.common.Services.java

/**
 * Returns a {@link Runnable} that can be used as a {@link ListenableFuture} listener to trigger
 * further service action or completing the result future. Used by
 * {@link #doChain(boolean, com.google.common.util.concurrent.Service, com.google.common.util.concurrent.Service...)}
 */// w  w  w  . ja  va2s . co  m
private static Runnable createChainListener(final ListenableFuture<Service.State> future,
        final Service[] services, final AtomicInteger idx, final List<ListenableFuture<Service.State>> result,
        final SettableFuture<List<ListenableFuture<Service.State>>> resultFuture, final boolean doStart) {
    return new Runnable() {

        @Override
        public void run() {
            result.add(future);
            int nextIdx = idx.getAndIncrement();
            if (nextIdx == services.length) {
                resultFuture.set(result);
                return;
            }
            ListenableFuture<Service.State> actionFuture = doStart ? services[nextIdx].start()
                    : services[nextIdx].stop();
            actionFuture.addListener(
                    createChainListener(actionFuture, services, idx, result, resultFuture, doStart),
                    Threads.SAME_THREAD_EXECUTOR);
        }
    };
}

From source file:com.continuuity.loom.common.zookeeper.ZKClientExt.java

private static <T> ListenableFuture<T> ignoreError(final ListenableFuture<T> future,
        final Class<? extends KeeperException> ex) {

    final SettableFuture<T> futureWithIgnoredError = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<T>() {
        @Override/* w w w.j  a  va  2 s.c  om*/
        public void onSuccess(T result) {
            futureWithIgnoredError.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (causedBy(t, ex)) {
                futureWithIgnoredError.set(null);
            } else {
                futureWithIgnoredError.setException(t);
            }
        }
    });

    return futureWithIgnoredError;
}

From source file:org.jenkinsci.plugins.workflow.support.concurrent.Futures.java

/**
 * Creates a {@code ListenableFuture} which has its value set immediately upon
 * construction. The getters just return the value. This {@code Future} can't
 * be canceled or timed out and its {@code isDone()} method always returns
 * {@code true}./*from ww  w .j av  a 2 s .  c om*/
 */
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
    SettableFuture<V> future = SettableFuture.create();
    future.set(value);
    return future;
}

From source file:io.airlift.discovery.client.CachingServiceSelector.java

private static <V> ListenableFuture<V> chainedCallback(ListenableFuture<V> future,
        final FutureCallback<? super V> callback, Executor executor) {
    final SettableFuture<V> done = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<V>() {
        @Override//from  ww  w .j a  v a  2 s .  c  o m
        public void onSuccess(V result) {
            try {
                callback.onSuccess(result);
            } finally {
                done.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            try {
                callback.onFailure(t);
            } finally {
                done.setException(t);
            }
        }
    }, executor);
    return done;
}

From source file:org.opendaylight.vpnservice.elan.l2gw.utils.ElanL2GatewayMulticastUtils.java

/**
 * Updates the remote mcast mac table for all the devices in this elan
 * includes all the dpn tep ips and other devices tep ips in broadcast
 * locator set./*from  ww  w .  ja  v  a 2 s  . c o  m*/
 *
 * @param elanName
 *            the elan to be updated
 * @return the listenable future
 */
public static ListenableFuture<Void> updateRemoteMcastMacOnElanL2GwDevices(String elanName) {
    SettableFuture<Void> future = SettableFuture.create();
    future.set(null);
    try {
        WriteTransaction transaction = broker.newWriteOnlyTransaction();
        for (L2GatewayDevice device : ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName).values()) {
            prepareRemoteMcastMacUpdateOnDevice(transaction, elanName, device);
        }
        return transaction.submit();
    } catch (Throwable e) {
        LOG.error("Failed to configure mcast mac on elan " + elanName, e);
    }
    return future;
}

From source file:org.opendaylight.vpnservice.elan.l2gw.utils.ElanL2GatewayMulticastUtils.java

/**
 * Delete remote mcast mac from Hwvtep node.
 *
 * @param nodeId/* w w  w  .  j a va 2 s  .c  om*/
 *            the node id
 * @param logicalSwitchName
 *            the logical switch name
 * @return the listenable future
 */
private static ListenableFuture<Void> deleteRemoteMcastMac(NodeId nodeId, String logicalSwitchName) {
    InstanceIdentifier<LogicalSwitches> logicalSwitch = HwvtepSouthboundUtils
            .createLogicalSwitchesInstanceIdentifier(nodeId, new HwvtepNodeName(logicalSwitchName));
    RemoteMcastMacsKey remoteMcastMacsKey = new RemoteMcastMacsKey(new HwvtepLogicalSwitchRef(logicalSwitch),
            new MacAddress(ElanConstants.UNKNOWN_DMAC));

    RemoteMcastMacs remoteMcast = HwvtepUtils.getRemoteMcastMac(broker, LogicalDatastoreType.OPERATIONAL,
            nodeId, remoteMcastMacsKey);
    if (remoteMcast != null) {
        LOG.info("Deleting RemoteMcastMacs entry on node: {} for logical switch: {}", nodeId.getValue(),
                logicalSwitchName);
        return HwvtepUtils.deleteRemoteMcastMac(broker, nodeId, remoteMcastMacsKey);
    }

    SettableFuture<Void> future = SettableFuture.create();
    future.set(null);
    return future;
}

From source file:org.opendaylight.vpnservice.elan.l2gw.utils.ElanL2GatewayMulticastUtils.java

/**
 * Update mcast macs for this elan./*from   ww w . j  a v a 2  s  . c  o  m*/
 * for all dpns in this elan  recompute and update broadcast group
 * for all l2gw devices in this elan recompute and update remote mcast mac entry
 *
 * @param elanName
 *            the elan name
 * @param device
 *            the device
 * @param updateThisDevice
 *            the update this device
 * @return the listenable future
 */
public static ListenableFuture<Void> updateMcastMacsForAllElanDevices(String elanName, L2GatewayDevice device,
        boolean updateThisDevice) {

    SettableFuture<Void> ft = SettableFuture.create();
    ft.set(null);

    ElanInstance elanInstance = elanInstanceManager.getElanInstanceByName(elanName);
    elanInterfaceManager.updateRemoteBroadcastGroupForAllElanDpns(elanInstance);

    List<DpnInterfaces> dpns = ElanUtils.getInvolvedDpnsInElan(elanName);

    ConcurrentMap<String, L2GatewayDevice> devices = ElanL2GwCacheUtils.getInvolvedL2GwDevices(elanName);

    List<IpAddress> dpnsTepIps = getAllTepIpsOfDpns(device, dpns);
    List<IpAddress> l2GwDevicesTepIps = getAllTepIpsOfL2GwDevices(devices);
    // if (allTepIps.size() < 2) {
    // LOG.debug("no other devices are found in the elan {}", elanName);
    // return ft;
    // }

    WriteTransaction transaction = broker.newWriteOnlyTransaction();
    if (updateThisDevice) {
        preapareRemoteMcastMacEntry(transaction, elanName, device, dpnsTepIps, l2GwDevicesTepIps);
    }

    // TODO: Need to revisit below logic as logical switches might not be
    // present to configure RemoteMcastMac entry
    for (L2GatewayDevice otherDevice : devices.values()) {
        if (!otherDevice.getDeviceName().equals(device.getDeviceName())) {
            preapareRemoteMcastMacEntry(transaction, elanName, otherDevice, dpnsTepIps, l2GwDevicesTepIps);
        }
    }
    return transaction.submit();

}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

public static void watchDeleted(final ZKClient zkClient, final String path,
        final SettableFuture<String> completion) {

    Futures.addCallback(zkClient.exists(path, new Watcher() {
        @Override/*from   w w w  .j a  va 2s  . c om*/
        public void process(WatchedEvent event) {
            if (!completion.isDone()) {
                if (event.getType() == Event.EventType.NodeDeleted) {
                    completion.set(path);
                } else {
                    watchDeleted(zkClient, path, completion);
                }
            }
        }
    }), new FutureCallback<Stat>() {
        @Override
        public void onSuccess(Stat result) {
            if (result == null) {
                completion.set(path);
            }
        }

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