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:org.thingsboard.server.controller.AssetController.java

@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/assets", params = { "assetIds" }, method = RequestMethod.GET)
@ResponseBody//from  w w w  .j  av  a2 s. c o  m
public List<Asset> getAssetsByIds(@RequestParam("assetIds") String[] strAssetIds) throws ThingsboardException {
    checkArrayParameter("assetIds", strAssetIds);
    try {
        SecurityUser user = getCurrentUser();
        TenantId tenantId = user.getTenantId();
        CustomerId customerId = user.getCustomerId();
        List<AssetId> assetIds = new ArrayList<>();
        for (String strAssetId : strAssetIds) {
            assetIds.add(new AssetId(toUUID(strAssetId)));
        }
        ListenableFuture<List<Asset>> assets;
        if (customerId == null || customerId.isNullUid()) {
            assets = assetService.findAssetsByTenantIdAndIdsAsync(tenantId, assetIds);
        } else {
            assets = assetService.findAssetsByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, assetIds);
        }
        return checkNotNull(assets.get());
    } catch (Exception e) {
        throw handleException(e);
    }
}

From source file:org.opendaylight.ovsdb.plugin.ConnectionService.java

private void initializeInventoryForNewNode(Connection connection)
        throws InterruptedException, ExecutionException {
    Channel channel = connection.getChannel();
    InetAddress address = ((InetSocketAddress) channel.remoteAddress()).getAddress();
    int port = ((InetSocketAddress) channel.remoteAddress()).getPort();
    IPAddressProperty addressProp = new IPAddressProperty(address);
    L4PortProperty l4Port = new L4PortProperty(port);
    Set<Property> props = new HashSet<Property>();
    props.add(addressProp);/* w ww  .jav a 2 s. c  o  m*/
    props.add(l4Port);
    inventoryServiceInternal.addNode(connection.getNode(), props);

    List<String> dbNames = Arrays.asList(Open_vSwitch.NAME.getName());
    ListenableFuture<DatabaseSchema> dbSchemaF = connection.getRpc().get_schema(dbNames);
    DatabaseSchema databaseSchema = dbSchemaF.get();
    inventoryServiceInternal.updateDatabaseSchema(connection.getNode(), databaseSchema);

    MonitorRequestBuilder monitorReq = new MonitorRequestBuilder();
    for (Table<?> table : Tables.getTables()) {
        if (databaseSchema.getTables().keySet().contains(table.getTableName().getName())) {
            monitorReq.monitor(table);
        } else {
            logger.debug("We know about table {} but it is not in the schema of {}",
                    table.getTableName().getName(), connection.getNode().getNodeIDString());
        }
    }

    ListenableFuture<TableUpdates> monResponse = connection.getRpc().monitor(monitorReq);
    TableUpdates updates = monResponse.get();
    if (updates.getError() != null) {
        logger.error("Error configuring monitor, error : {}, details : {}", updates.getError(),
                updates.getDetails());
        /* FIXME: This should be cause for alarm */
        throw new RuntimeException("Failed to setup a monitor in OVSDB");
    }
    UpdateNotification monitor = new UpdateNotification();
    monitor.setUpdate(updates);
    this.update(connection.getNode(), monitor);
    if (autoConfigureController) {
        this.updateOFControllers(connection.getNode());
    }
    inventoryServiceInternal.notifyNodeAdded(connection.getNode());
}

From source file:org.opendaylight.alto.services.provider.simple.SimpleAltoService.java

private void updatePrivateNetworkMap() {
    InstanceIdentifier<NetworkMap> niid = getNetworkMapIID(PRIV_NETWORK_MAP);
    try {/*from  ww  w  . j  a  v  a2 s.  c o  m*/
        ReadOnlyTransaction tx = m_db.newReadOnlyTransaction();
        ListenableFuture<Optional<NetworkMap>> result = tx.read(LogicalDatastoreType.CONFIGURATION, niid);
        if (result.get().isPresent()) {
            NetworkMap privateNetworkMap = result.get().get();
            iHelper.update(privateNetworkMap);
        } else {
            m_logger.info("Failed to read with niid: {}", niid);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opendaylight.alto.services.provider.simple.SimpleAltoService.java

@Override
public RFC7285IRD getDefaultIRD() {
    InstanceIdentifier<IRD> iid = getIRDIID();

    try {//from w w  w.j a  va2 s.c  o  m
        ReadOnlyTransaction tx = m_db.newReadOnlyTransaction();
        ListenableFuture<Optional<IRD>> result = tx.read(LogicalDatastoreType.CONFIGURATION, iid);
        if (result.get().isPresent()) {
            IRD iIRD = result.get().get();
            m_logger.info(iIRD.toString());
            m_logger.info(m_mapper.writeValueAsString(iIRD));
            ObjectNode node = m_mapper.valueToTree(iIRD);

            RFC7285IRD ret = m_irdconverter.convert(node);
            m_logger.info("IRD convert compelete.");
            return ret;
        } else {
            m_logger.info("Failed to read with ciid: {}", iid);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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

/**
 * Asynchronously write to datastore with distributed-tx API
 *//*from  ww  w  .  jav a 2s.  com*/
@Override
public void writeData() {
    int putsPerTx = input.getPutsPerTx();
    int counter = 0;

    InstanceIdentifier<DatastoreTestData> nodeId = InstanceIdentifier.create(DatastoreTestData.class);
    List<ListenableFuture<Void>> putFutures = new ArrayList<ListenableFuture<Void>>((int) putsPerTx);
    List<OuterList> outerLists = dataStoreListBuilder.buildOuterList();

    if (input.getOperation() == OperationType.DELETE) {
        dataStoreListBuilder.buildTestInnerList();
    }

    dtx = dTxProvider.newTx(nodesMap);
    startTime = System.nanoTime();
    for (OuterList outerList : outerLists) {
        for (InnerList innerList : outerList.getInnerList()) {
            InstanceIdentifier<InnerList> innerIid = InstanceIdentifier.create(DatastoreTestData.class)
                    .child(OuterList.class, outerList.getKey()).child(InnerList.class, innerList.getKey());

            CheckedFuture<Void, DTxException> writeFuture;
            if (input.getOperation() == OperationType.PUT) {
                writeFuture = dtx.putAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else if (input.getOperation() == OperationType.MERGE) {
                writeFuture = dtx.mergeAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, innerList, nodeId);
            } else {
                writeFuture = dtx.deleteAndRollbackOnFailure(DTXLogicalTXProviderType.DATASTORE_TX_PROVIDER,
                        LogicalDatastoreType.CONFIGURATION, innerIid, nodeId);
            }
            putFutures.add(writeFuture);
            counter++;

            if (counter == putsPerTx) {
                //Aggregate all the put futures into a listenable future which can ensure all asynchronous writes has been finished
                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(nodesMap);
                putFutures = new ArrayList<ListenableFuture<Void>>(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();
}

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

@Override
public AtriumInterface getInterface(NodeConnector connectPoint) {

    NodeConnectorId connectorId = connectPoint.getId();
    String splitArray[] = connectorId.getValue().split(":");

    String dpid = splitArray[0] + ":" + splitArray[1];
    String ofPortId = splitArray[2];

    ReadOnlyTransaction readOnlyTransaction = dataBroker.newReadOnlyTransaction();

    InstanceIdentifier<Addresses> addressBuilder = InstanceIdentifier.builder(Addresses.class).build();

    Addresses addresses = null;/* w  w  w .  ja  v  a  2 s  .c om*/

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

    for (Address address : addresses.getAddress()) {

        if (dpid.equals(address.getDpid()) && ofPortId.equals(address.getOfPortId().getValue())) {
            MacAddress mac = address.getMac();
            AtriumVlanId vlanId = AtriumVlanId.vlanId(address.getVlan().shortValue());

            IpAddress ipAddress = address.getIpAddress();
            AtriumIp4Address ip4Address = AtriumIp4Address.valueOf(ipAddress.getIpv4Address().getValue());

            // TODO
            // Include subnet in yang
            AtriumIp4Prefix ip4Prefix = AtriumIp4Prefix.valueOf(ip4Address.getIp4Address().toString() + "/24");
            AtriumInterfaceIpAddress interfaceIpAddress = new AtriumInterfaceIpAddress(ip4Address, ip4Prefix);
            Set<AtriumInterfaceIpAddress> interfaceIpAddressSet = new HashSet<>();
            interfaceIpAddressSet.add(interfaceIpAddress);

            AtriumInterface matchingInterface = new AtriumInterface(connectPoint, interfaceIpAddressSet, mac,
                    vlanId);
            return matchingInterface;
        }
    }

    return null;
}

From source file:org.opendaylight.alto.services.provider.simple.SimpleAltoService.java

@Override
public RFC7285CostMap getCostMap(String id) {
    m_logger.info("Handling cost-map resource: {}", id);
    InstanceIdentifier<CostMap> ciid = getCostMapIID(id);
    m_logger.info("CostMap IID: {}", ciid);

    try {//from  w ww .  j  a  v a2s. c  o  m
        ReadOnlyTransaction tx = m_db.newReadOnlyTransaction();
        ListenableFuture<Optional<CostMap>> result = tx.read(LogicalDatastoreType.CONFIGURATION, ciid);
        if (result.get().isPresent()) {
            CostMap cm = result.get().get();
            m_logger.info(cm.toString());
            m_logger.info(m_mapper.writeValueAsString(cm));
            ObjectNode node = m_mapper.valueToTree(cm);

            RFC7285CostMap ret = m_cmconverter.convert(node);
            return ret;
        } else {
            m_logger.info("Failed to read with ciid: {}", ciid);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.opendaylight.alto.services.provider.simple.SimpleAltoService.java

@Override
public RFC7285NetworkMap getNetworkMap(String id) {
    m_logger.info("Handling resource-id: {}", id);
    InstanceIdentifier<NetworkMap> niid = getNetworkMapIID(id);
    m_logger.info("IID: {}", niid);

    try {// w ww  .ja v  a2s.c o  m
        ReadOnlyTransaction tx = m_db.newReadOnlyTransaction();
        ListenableFuture<Optional<NetworkMap>> result = tx.read(LogicalDatastoreType.CONFIGURATION, niid);
        if (result.get().isPresent()) {
            NetworkMap nm = result.get().get();
            ObjectNode node = m_mapper.valueToTree(nm);
            m_logger.info(m_mapper.writeValueAsString(nm));

            RFC7285NetworkMap ret = m_nmconverter.convert(node);
            return ret;
        } else {
            m_logger.info("Failed to read with niid: {}", niid);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.robotninjas.barge.log.RaftLogBase.java

public ListenableFuture<SnapshotInfo> performSnapshot() throws RaftException {
    SnapshotInfo snapshotInfo;/*from  w  w w . j a  v a 2  s.c  o m*/
    try {
        Snapshotter snapshotter;
        synchronized (this) {
            ListenableFuture<Snapshotter> snapshotterFuture = stateMachine.prepareSnapshot(currentTerm,
                    lastApplied);
            snapshotter = snapshotterFuture.get();
        }

        snapshotInfo = snapshotter.finishSnapshot();
    } catch (Exception e) {
        LOGGER.error("Error during snapshot", e);
        throw RaftException.propagate(e);
    }

    LOGGER.info("Wrote snapshot {}", snapshotInfo);

    ListenableFuture<Object> entryFuture = proposeEntry(Entry.newBuilder().setSnapshot(snapshotInfo));

    return Futures.transform(entryFuture, G8.fn((result) -> {
        //      if (!Objects.equal(result, Boolean.TRUE))
        //        throw new IllegalStateException();
        this.lastSnapshot = snapshotInfo;
        return snapshotInfo;
    }));
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbClientImpl.java

@Override
public <E extends TableSchema<E>> TableUpdates monitor(final DatabaseSchema dbSchema,
        List<MonitorRequest<E>> monitorRequest, final MonitorCallBack callback) {

    final ImmutableMap<String, MonitorRequest<E>> reqMap = Maps.uniqueIndex(monitorRequest,
            new Function<MonitorRequest<E>, String>() {
                @Override/*from  w w  w.  j a  v a2  s  .  c  om*/
                public String apply(MonitorRequest<E> input) {
                    return input.getTableName();
                }
            });

    final MonitorHandle monitorHandle = new MonitorHandle(UUID.randomUUID().toString());
    registerCallback(monitorHandle, callback, dbSchema);

    ListenableFuture<JsonNode> monitor = rpc.monitor(new Params() {
        @Override
        public List<Object> params() {
            return Lists.<Object>newArrayList(dbSchema.getName(), monitorHandle.getId(), reqMap);
        }
    });
    JsonNode result;
    try {
        result = monitor.get();
    } catch (InterruptedException | ExecutionException e) {
        return null;
    }
    TableUpdates updates = transformingCallback(result, dbSchema);
    return updates;
}