Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:io.datakernel.service.ServiceGraph.java

private ListenableFuture<LongestPath> combineDependenciesFutures(List<ListenableFuture<LongestPath>> futures,
        Executor executor) {/*from w w w  .j  av a 2s  .  com*/
    if (futures.size() == 0) {
        return Futures.immediateFuture(null);
    }
    if (futures.size() == 1) {
        return futures.get(0);
    }

    final SettableFuture<LongestPath> settableFuture = SettableFuture.create();
    final AtomicInteger atomicInteger = new AtomicInteger(futures.size());
    final AtomicReference<LongestPath> bestPath = new AtomicReference<>();
    final AtomicReference<Throwable> exception = new AtomicReference<>();
    for (final ListenableFuture<LongestPath> future : futures) {
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    LongestPath path = future.get();
                    if (bestPath.get() == null || (path != null && path.totalTime > bestPath.get().totalTime)) {
                        bestPath.set(path);
                    }
                } catch (InterruptedException | ExecutionException e) {
                    if (exception.get() == null) {
                        exception.set(getRootCause(e));
                    }
                }
                if (atomicInteger.decrementAndGet() == 0) {
                    if (exception.get() != null) {
                        settableFuture.setException(exception.get());
                    } else {
                        settableFuture.set(bestPath.get());
                    }
                }
            }
        }, executor);
    }
    return settableFuture;
}

From source file:org.apache.druid.server.coordinator.CostBalancerStrategy.java

@Override
public Iterator<ServerHolder> pickServersToDrop(DataSegment toDrop, NavigableSet<ServerHolder> serverHolders) {
    List<ListenableFuture<Pair<Double, ServerHolder>>> futures = Lists.newArrayList();

    for (final ServerHolder server : serverHolders) {
        futures.add(exec.submit(() -> Pair.of(computeCost(toDrop, server, true), server)));
    }//from w  w  w  .  j  ava2  s.c  om

    final ListenableFuture<List<Pair<Double, ServerHolder>>> resultsFuture = Futures.allAsList(futures);

    try {
        // results is an un-ordered list of a pair consisting of the 'cost' of a segment being on a server and the server
        List<Pair<Double, ServerHolder>> results = resultsFuture.get();
        return results.stream()
                // Comparator.comapringDouble will order by lowest cost...
                // reverse it because we want to drop from the highest cost servers first
                .sorted(Comparator.comparingDouble((Pair<Double, ServerHolder> o) -> o.lhs).reversed())
                .map(x -> x.rhs).collect(Collectors.toList()).iterator();
    } catch (Exception e) {
        log.makeAlert(e, "Cost Balancer Multithread strategy wasn't able to complete cost computation.").emit();
    }
    return Collections.emptyIterator();
}

From source file:org.opendaylight.atrium.routingservice.config.RoutingConfigServiceImpl.java

@Override
public BgpPeers getBgpPeers() {
    BgpPeers localBgpPeers = null;/*from w w w  .  ja v  a  2  s . c  o m*/
    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
    InstanceIdentifier<BgpPeers> bgpPeersBuilder = InstanceIdentifier.builder(BgpPeers.class).build();

    try {
        ListenableFuture<Optional<BgpPeers>> lfONT;
        lfONT = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, bgpPeersBuilder);
        Optional<BgpPeers> oNT = lfONT.get();
        localBgpPeers = oNT.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } finally {
        readOnlyTransaction.close();
    }
    return localBgpPeers;
}

From source file:org.opendaylight.atrium.hostservice.impl.HostMonitor.java

private boolean isNodeConnectorInternal(NodeConnector nodeConnector) {
    TpId tpId = new TpId(nodeConnector.getKey().getId().getValue());
    InstanceIdentifier<NetworkTopology> ntII = InstanceIdentifier.builder(NetworkTopology.class).build();
    ListenableFuture<Optional<NetworkTopology>> lfONT;
    try (ReadOnlyTransaction rot = dataService.newReadOnlyTransaction()) {
        lfONT = rot.read(LogicalDatastoreType.OPERATIONAL, ntII);
        rot.close();/* w  ww . j  a v  a2 s .c  o m*/
    }
    Optional<NetworkTopology> oNT;
    try {
        oNT = lfONT.get();
    } catch (InterruptedException | ExecutionException ex) {
        LOG.warn(ex.getLocalizedMessage());
        return false;
    }
    if (oNT != null && oNT.isPresent()) {
        NetworkTopology networkTopo = oNT.get();
        for (Topology t : networkTopo.getTopology()) {
            if (t.getLink() != null) {
                for (Link l : t.getLink()) {
                    if ((l.getSource().getSourceTp().equals(tpId)
                            && !l.getDestination().getDestTp().getValue().startsWith(Host.NODE_PREFIX))
                            || (l.getDestination().getDestTp().equals(tpId)
                                    && !l.getSource().getSourceTp().getValue().startsWith(Host.NODE_PREFIX))) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

From source file:org.opendaylight.atrium.routingservice.config.RoutingConfigServiceImpl.java

@Override
public BgpPeer getBgpPeerByIpAddress(IpAddress ip) {
    if (ip == null) {
        return null;
    }/*from   ww w .j  a v  a 2  s  .  com*/

    BgpPeer bgpPeer = null;
    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();

    // IpAddress ipAddress = new IpAddress(new Ipv4Address(ip));

    BgpPeerKey bgpPeerKey = new BgpPeerKey(ip);

    InstanceIdentifier<BgpPeer> bgpPeerBuilder = InstanceIdentifier.builder(BgpPeers.class)
            .child(BgpPeer.class, bgpPeerKey).build();

    try {
        ListenableFuture<Optional<BgpPeer>> lfONT;
        lfONT = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, bgpPeerBuilder);
        Optional<BgpPeer> oNT = lfONT.get();
        bgpPeer = oNT.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } finally {
        readOnlyTransaction.close();
    }
    return bgpPeer;
}

From source file:org.opendaylight.atrium.routingservice.config.RoutingConfigServiceImpl.java

@Override
public BgpSpeakers getBgpSpeakers() {
    BgpSpeakers localBgpSpeakers = null;
    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
    InstanceIdentifier<BgpSpeakers> bgpSpeakersBuilder = InstanceIdentifier.builder(BgpSpeakers.class).build();

    try {/* ww  w .  j  a v  a  2 s . co m*/
        ListenableFuture<Optional<BgpSpeakers>> lfONT;
        lfONT = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, bgpSpeakersBuilder);
        Optional<BgpSpeakers> oNT = lfONT.get();
        localBgpSpeakers = oNT.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } finally {
        readOnlyTransaction.close();
    }
    return localBgpSpeakers;
}

From source file:org.opendaylight.atrium.routingservice.config.RoutingConfigServiceImpl.java

@Override
public BgpSpeaker getBgpSpeakerByMac(String mac) {
    BgpSpeaker bgpSpeaker = null;/*from  w w  w  . j  a v a  2  s  .c  o m*/
    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();
    MacAddress macAddress = new MacAddress(mac);

    BgpSpeakerKey bgpSpeakerKey = new BgpSpeakerKey(macAddress);
    InstanceIdentifier<BgpSpeaker> bgpSpeakerBuilder = InstanceIdentifier.builder(BgpSpeakers.class)
            .child(BgpSpeaker.class, bgpSpeakerKey).build();

    try {
        ListenableFuture<Optional<BgpSpeaker>> lfONT;
        lfONT = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, bgpSpeakerBuilder);
        Optional<BgpSpeaker> oNT = lfONT.get();
        bgpSpeaker = oNT.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } finally {
        readOnlyTransaction.close();
    }

    return bgpSpeaker;
}

From source file:com.cloudera.hadoop.hdfs.nfs.rpc.ClientInputHandler.java

private void execute(final SessionSecurityHandler<? extends Verifier> securityHandler,
        AccessPrivilege accessPrivilege, final RPCRequest request, RPCBuffer requestBuffer)
        throws RPCException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(mSessionID + " starting xid " + request.getXidAsHexString());
    }//from   www.j a v  a  2  s  . co m
    mHandler.beforeProcess(request);
    REQUEST applicationRequest = mHandler.createRequest();
    applicationRequest.read(requestBuffer);
    if (applicationRequest instanceof RequiresCredentials) {
        RequiresCredentials requiresCredentials = (RequiresCredentials) applicationRequest;
        // check to ensure it's auth creds is above
        requiresCredentials.setCredentials((AuthenticatedCredentials) request.getCredentials());
    }
    final ListenableFuture<RESPONSE> future = mHandler.process(request, applicationRequest, accessPrivilege,
            mClient.getInetAddress(), mSessionID);
    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                writeApplicationResponse(securityHandler, request, future.get());
            } catch (Throwable t) {
                LOGGER.error("Unexpected error processing request", t);
            }
        }
    }, MoreExecutors.sameThreadExecutor());
}

From source file:org.opendaylight.l2switch.hosttracker.plugin.internal.HostTrackerImpl.java

/**
 * It verifies if a given NodeConnector is *internal*. An *internal*
 * NodeConnector is considered to be all NodeConnetors that are NOT attached
 * to hosts created by hosttracker./*from   w  ww  . j a v a2s .co  m*/
 *
 * @param nodeConnector the nodeConnector to check if it is internal or not.
 * @return true if it was found a host connected to this nodeConnetor, false
 * if it was not found a network topology or it was not found a host
 * connected to this nodeConnetor.
 */
private boolean isNodeConnectorInternal(NodeConnector nodeConnector) {
    TpId tpId = new TpId(nodeConnector.getKey().getId().getValue());
    InstanceIdentifier<NetworkTopology> ntII = InstanceIdentifier.builder(NetworkTopology.class).build();
    ListenableFuture<Optional<NetworkTopology>> lfONT;
    try (ReadOnlyTransaction rot = dataService.newReadOnlyTransaction()) {
        lfONT = rot.read(LogicalDatastoreType.OPERATIONAL, ntII);
        rot.close();
    }
    Optional<NetworkTopology> oNT;
    try {
        oNT = lfONT.get();
    } catch (InterruptedException | ExecutionException ex) {
        log.warn(ex.getLocalizedMessage());
        return false;
    }
    if (oNT != null && oNT.isPresent()) {
        NetworkTopology networkTopo = oNT.get();
        for (Topology t : networkTopo.getTopology()) {
            if (t.getLink() != null) {
                for (Link l : t.getLink()) {
                    if ((l.getSource().getSourceTp().equals(tpId)
                            && !l.getDestination().getDestTp().getValue().startsWith(Host.NODE_PREFIX))
                            || (l.getDestination().getDestTp().equals(tpId)
                                    && !l.getSource().getSourceTp().getValue().startsWith(Host.NODE_PREFIX))) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

From source file:org.opendaylight.distributed.tx.it.provider.datawriter.DtxNetconfAsyncWriter.java

/**
 * Asynchronously write configuration to NetConf device with distributed-tx API
 */// w  ww .j  a va 2 s  .  c o  m
@Override
public void writeData() {
    int putsPerTx = input.getPutsPerTx();
    int counter = 0;
    List<ListenableFuture<Void>> putFutures = new ArrayList<ListenableFuture<Void>>(putsPerTx);
    List<NodeId> nodeIdList = new ArrayList(this.nodeIdSet);
    Set<InstanceIdentifier<?>> txIidSet = new HashSet<>();
    NodeId nodeId = nodeIdList.get(0);
    InstanceIdentifier msNodeId = NETCONF_TOPO_IID.child(Node.class, new NodeKey(nodeId));
    InterfaceName ifName = nodeIfList.get(nodeId).get(0);

    if (input.getOperation() == OperationType.DELETE) {
        //Build subInterfaces for delete operation
        configInterface();
    }

    txIidSet.add(msNodeId);
    dtx = dTxProvider.newTx(txIidSet);
    startTime = System.nanoTime();
    for (int i = 1; i <= input.getLoop(); i++) {
        KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> specificInterfaceCfgIid = netconfIid
                .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                        new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), ifName));

        InterfaceConfigurationBuilder interfaceConfigurationBuilder = new InterfaceConfigurationBuilder();
        interfaceConfigurationBuilder.setInterfaceName(ifName);
        interfaceConfigurationBuilder
                .setDescription(DTXITConstants.TEST_DESCRIPTION + input.getOperation() + i);
        interfaceConfigurationBuilder.setActive(new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE));
        InterfaceConfiguration config = interfaceConfigurationBuilder.build();

        CheckedFuture<Void, DTxException> writeFuture = null;
        if (input.getOperation() == OperationType.PUT) {
            //Put configuration to the same interface
            writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId);
        } else if (input.getOperation() == OperationType.MERGE) {
            //Merge configuration to the same interface
            writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, specificInterfaceCfgIid, config, msNodeId);
        } else {
            //Delete subInterfaces
            InterfaceName subIfName = new InterfaceName(DTXITConstants.INTERFACE_NAME_PREFIX + i);
            KeyedInstanceIdentifier<InterfaceConfiguration, InterfaceConfigurationKey> subSpecificInterfaceCfgIid = netconfIid
                    .child(InterfaceConfiguration.class, new InterfaceConfigurationKey(
                            new InterfaceActive(DTXITConstants.INTERFACE_ACTIVE), subIfName));
            writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.NETCONF_TX_PROVIDER,
                    LogicalDatastoreType.CONFIGURATION, subSpecificInterfaceCfgIid, msNodeId);
        }
        putFutures.add(writeFuture);
        counter++;

        if (counter == putsPerTx) {
            ListenableFuture<Void> aggregatePutFuture = Futures.transform(Futures.allAsList(putFutures),
                    new Function<List<Void>, Void>() {
                        @Nullable
                        @Override
                        public Void apply(@Nullable List<Void> voids) {
                            return null;
                        }
                    });
            try {
                aggregatePutFuture.get();
                CheckedFuture<Void, TransactionCommitFailedException> submitFuture = dtx.submit();
                try {
                    submitFuture.checkedGet();
                    txSucceed++;
                } catch (TransactionCommitFailedException e) {
                    txError++;
                }
            } catch (Exception e) {
                txError++;
                dtx.cancel();
            }

            counter = 0;
            dtx = dTxProvider.newTx(txIidSet);
            putFutures = new ArrayList<ListenableFuture<Void>>((int) putsPerTx);
        }
    }

    ListenableFuture<Void> aggregatePutFuture = Futures.transform(Futures.allAsList(putFutures),
            new Function<List<Void>, Void>() {
                @Nullable
                @Override
                public Void apply(@Nullable List<Void> voids) {
                    return null;
                }
            });

    try {
        aggregatePutFuture.get();
        CheckedFuture<Void, TransactionCommitFailedException> restSubmitFuture = dtx.submit();
        try {
            restSubmitFuture.checkedGet();
            txSucceed++;
        } catch (Exception e) {
            txError++;
        }
    } catch (Exception e) {
        txError++;
    }
    endTime = System.nanoTime();
}