Example usage for com.google.common.util.concurrent CheckedFuture checkedGet

List of usage examples for com.google.common.util.concurrent CheckedFuture checkedGet

Introduction

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

Prototype

V checkedGet() throws X;

Source Link

Document

Exception checking version of Future#get() that will translate InterruptedException , CancellationException and ExecutionException into application-specific exceptions.

Usage

From source file:org.opendaylight.neutron.transcriber.AbstractNeutronInterface.java

private <T extends DataObject> T readMd(InstanceIdentifier<T> path, ReadTransaction tx) {
    Preconditions.checkNotNull(tx);/*from  w ww  .  j av a 2  s .  c  o  m*/
    T result = null;
    final CheckedFuture<Optional<T>, ReadFailedException> future = tx.read(LogicalDatastoreType.CONFIGURATION,
            path);
    if (future != null) {
        Optional<T> optional;
        try {
            optional = future.checkedGet();
            if (optional.isPresent()) {
                result = optional.get();
            }
        } catch (final ReadFailedException e) {
            LOGGER.warn("Failed to read {}", path, e);
        }
    }
    return result;
}

From source file:com.highstreet.technologies.odl.app.impl.ClosedLoopAutomationImpl.java

/**
 * Read configuration of the Timer from the config datastore
 * @return//from  ww w  .j  av a2s .  com
  */
@Override
public Future<RpcResult<ReadTimerOutput>> readTimer() {
    ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();

    CheckedFuture<Optional<TimerConfig>, ReadFailedException> timerSettingFuture = transaction
            .read(LogicalDatastoreType.CONFIGURATION, TIMER_SETTING_PATH);
    ReadTimerOutputBuilder readTimerOutputBuilder = new ReadTimerOutputBuilder();
    try {
        Optional<TimerConfig> opt = timerSettingFuture.checkedGet();
        TimerConfig timerSetting = opt.get();
        readTimerOutputBuilder.setEnabled(timerSetting.isEnabled());
        readTimerOutputBuilder.setOption(timerSetting.getOption());
    } catch (Exception e) {
        // if node of the config datastore is empty, we will return default timer setting
        readTimerOutputBuilder.setEnabled(TIMER_DEFAULT_ENABLED);
        readTimerOutputBuilder.setOption(TIMER_DEFAULT_OPTION);
    }
    return RpcResultBuilder.success(readTimerOutputBuilder.build()).buildFuture();
}

From source file:org.dcache.srm.request.GetFileRequest.java

@Override
protected void stateChanged(State oldState) {
    State state = getState();//from   www.  j av  a2 s  . c o m
    LOGGER.debug("State changed from {} to {}", oldState, getState());
    switch (state) {
    case READY:
        try {
            getContainerRequest().resetRetryDeltaTime();
        } catch (SRMInvalidRequestException ire) {
            LOGGER.error(ire.toString());
        }
        break;

    case DONE:
    case FAILED:
    case CANCELED:
        AbstractStorageElement storage = getStorage();
        try {
            SRMUser user = getUser();
            String fileId = getFileId();
            String pinId = getPinId();
            if (fileId != null && pinId != null) {
                LOGGER.info("State changed to final state, unpinning fileId = {} pinId = {}.", fileId, pinId);
                CheckedFuture<String, ? extends SRMException> future = storage.unPinFile(null, fileId, pinId);
                future.addListener(() -> {
                    try {
                        LOGGER.debug("Unpinned (pinId={}).", future.checkedGet());
                    } catch (SRMException e) {
                        LOGGER.error("Unpinning failed: {}", e.getMessage());
                    }
                }, MoreExecutors.directExecutor());
            } else {
                BringOnlineFileRequest.unpinBySURLandRequestToken(storage, user, String.valueOf(getRequestId()),
                        getSurl());
            }
        } catch (SRMInternalErrorException | SRMInvalidRequestException e) {
            LOGGER.error(e.toString());
        }
    }

    super.stateChanged(oldState);
}

From source file:org.dcache.srm.request.BringOnlineFileRequest.java

@Override
protected void stateChanged(State oldState) {
    State state = getState();/*from   w  w  w. ja v a2 s  .co m*/
    LOGGER.debug("State changed from {} to {}", oldState, getState());
    switch (state) {
    case READY:
        try {
            getContainerRequest().resetRetryDeltaTime();
        } catch (SRMInvalidRequestException ire) {
            LOGGER.error(ire.toString());
        }
        break;
    case CANCELED:
    case FAILED:
        try {
            SRMUser user = getUser();
            String pinId = getPinId();
            String fileId = getFileId();
            AbstractStorageElement storage = getStorage();
            if (fileId != null && pinId != null) {
                LOGGER.info("State changed to final state, unpinning fileId = {} pinId = {}.", fileId, pinId);
                CheckedFuture<String, ? extends SRMException> future = storage.unPinFile(null, fileId, pinId);
                future.addListener(() -> {
                    try {
                        LOGGER.debug("File unpinned (pinId={}).", future.checkedGet());
                    } catch (SRMException e) {
                        LOGGER.error("Unpinning failed: {}", e.getMessage());
                    }

                }, MoreExecutors.directExecutor());
            } else {
                unpinBySURLandRequestToken(storage, user, String.valueOf(getRequestId()), getSurl());
            }
        } catch (SRMInternalErrorException | SRMInvalidRequestException ire) {
            LOGGER.error(ire.toString());
        }
        break;
    }
    super.stateChanged(oldState);
}

From source file:org.opendaylight.netvirt.federation.plugin.FederationPluginMgr.java

private Set<String> getRemoteSitesToBeRemovedAndCleanState(UpdateFederatedNetworksInput input) {
    Set<String> candidateSitesToRemove = new HashSet<>();
    ReadOnlyTransaction readTx = db.newReadOnlyTransaction();
    InstanceIdentifier<FederatedNetworks> existingNetworksPath = InstanceIdentifier
            .create(FederatedNetworks.class);
    CheckedFuture<Optional<FederatedNetworks>, ReadFailedException> existingNetworksFuture = readTx
            .read(LogicalDatastoreType.CONFIGURATION, existingNetworksPath);
    readTx.close();//from  w  w  w .j av a2 s .c  om
    Optional<FederatedNetworks> existingNetsOptional = null;
    try {
        existingNetsOptional = existingNetworksFuture.checkedGet();
    } catch (ReadFailedException e) {
        LOG.error("Error while reading existing networks", e);
        return candidateSitesToRemove;
    }
    if (existingNetsOptional.isPresent()) {
        for (FederatedNetwork existingNet : existingNetsOptional.get().getFederatedNetwork()) {
            boolean foundExistingNetInNewInput = false;
            for (FederatedNetworksIn inputNet : input.getFederatedNetworksIn()) {
                if (existingNet.getSelfNetId() == inputNet.getSelfNetId()) {
                    foundExistingNetInNewInput = true;
                    break;
                }
            }
            if (!foundExistingNetInNewInput) {
                // Add the sites which was updated to the sites that we
                // should check for removal
                // subscribeIngressPlugins will make the final decision on
                // which sites to keep
                for (SiteNetwork siteNet : existingNet.getSiteNetwork()) {
                    candidateSitesToRemove.add(siteNet.getSiteIp());
                }
                // delete this network from Config
                deleteFederatedNetFromConfigDs(existingNet.getSelfNetId());
            }
        }
    }
    return candidateSitesToRemove;
}

From source file:org.opendaylight.proxyarp.ProxyArp.java

public Node getNodeFromIID(InstanceIdentifier<Node> nodeIID) {
    ReadOnlyTransaction rtx = dataBroker.newReadOnlyTransaction();
    CheckedFuture<Optional<Node>, ReadFailedException> future = rtx.read(LogicalDatastoreType.OPERATIONAL,
            nodeIID);//from   ww  w .ja va 2 s .  com

    Optional<Node> optional = Optional.absent();
    try {
        optional = future.checkedGet();
        if (optional.isPresent()) {
            return optional.get();
        }
    } catch (ReadFailedException e) {
        LOG.error("can read the node specified by node iid : {}", nodeIID);
    }
    LOG.info("didn't find the node {}", nodeIID);
    return null;
}

From source file:org.opendaylight.alto.basic.impl.AltoModelConfigImpl.java

protected QueryOutput readResourceCostMap(String rid, final ReadTransaction rx) {
    InstanceIdentifier<ResourceCostMap> iid = ManualMapsUtils.getResourceCostMapIID(rid);
    CheckedFuture<Optional<ResourceCostMap>, ReadFailedException> future = rx
            .read(LogicalDatastoreType.OPERATIONAL, iid);
    Optional<ResourceCostMap> optional = Optional.absent();

    QueryOutputBuilder outputBuilder = new QueryOutputBuilder();
    outputBuilder.setType(ResourceTypeConfig.class);
    ConfigResponseBuilder crBuilder = new ConfigResponseBuilder();
    ConfigResponseMessageBuilder crmBuilder = new ConfigResponseMessageBuilder();
    ConfigResponseData1Builder crdBuilder = new ConfigResponseData1Builder();

    ResourceCostMap result = null;//from   w ww  . j  ava  2 s .com
    String errorCode = RESPONSE_ERROR_CODE_FAILED;

    try {
        optional = future.checkedGet();
        if (optional.isPresent()) {
            result = optional.get();
            crdBuilder.setConfigCostmapResponseData(
                    new ConfigCostmapResponseDataBuilder().setResourceId(result.getResourceId())
                            .setTag(result.getTag()).setMeta(result.getMeta()).setMap(result.getMap()).build());
            errorCode = RESPONSE_ERROR_CODE_OK;
        }
    } catch (Exception e) {
        LOG.warn("Reading resource failed! ResourceId: " + rid);
    }
    crmBuilder.setMeta((Meta) new Meta1Builder().setConfigResponseErrorCode(errorCode).build())
            .setConfigResponseData((ConfigResponseData) crdBuilder.build());
    crBuilder.setConfigResponseMessage(crmBuilder.build());
    outputBuilder.setResponse(crBuilder.build());
    return outputBuilder.build();
}

From source file:org.opendaylight.ofconfig.southbound.impl.OFconfigTestBase.java

protected void initMountService(NodeId netconfNodeId) {
    try {//  www  .j  av  a  2  s.co m

        final CapableSwitchBuilder capableSwitchBuilder = new CapableSwitchBuilder();
        capableSwitchBuilder.setConfigVersion("1.4").setId("ofconf-device");

        ControllersBuilder ctlllerBuilder = new ControllersBuilder();

        List<Controller> ctllers = new ArrayList<>();

        ControllerBuilder builder = new ControllerBuilder();

        builder.setId(new OFConfigId("test_ctl_new")).setKey(new ControllerKey(new OFConfigId("test_ctl_new")))
                .setProtocol(Protocol.Tcp).setIpAddress(IpAddressBuilder.getDefaultInstance("127.0.0.1"))
                .setPort(PortNumber.getDefaultInstance("6630"));

        ctllers.add(builder.build());

        ctlllerBuilder.setController(ctllers);

        LogicalSwitchesBuilder lsBuilder = new LogicalSwitchesBuilder();

        List<Switch> swlists = Lists.newArrayList();

        SwitchBuilder switchBuilder = new SwitchBuilder();
        switchBuilder.setId(new OFConfigId("test_sw")).setKey(new SwitchKey(new OFConfigId("test_sw")))
                .setControllers(ctlllerBuilder.build())
                .setDatapathId(new DatapathIdType("00:00:7a:31:cd:91:04:40"));

        swlists.add(switchBuilder.build());

        lsBuilder.setSwitch(swlists);
        capableSwitchBuilder.setLogicalSwitches(lsBuilder.build());

        CheckedFuture resultFuture = mock(CheckedFuture.class);

        Answer<Optional<CapableSwitch>> capableSwitchAnswer = new Answer<Optional<CapableSwitch>>() {

            @Override
            public Optional<CapableSwitch> answer(InvocationOnMock invocation) throws Throwable {
                return Optional.of(
                        capableSwitchRef.get() == null ? capableSwitchBuilder.build() : capableSwitchRef.get());
            }

        };

        when(resultFuture.checkedGet()).thenAnswer(capableSwitchAnswer);

        when(resultFuture.get()).thenAnswer(capableSwitchAnswer);

        InstanceIdentifier<CapableSwitch> iid = InstanceIdentifier.create(CapableSwitch.class);

        ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
        when(rtx.read(LogicalDatastoreType.CONFIGURATION, iid)).thenReturn(resultFuture);

        WriteTransaction wtx = mock(WriteTransaction.class);

        Mockito.doAnswer(new WriteTransactionAnswer(capableSwitchRef)).when(wtx).put(
                Matchers.eq(LogicalDatastoreType.CONFIGURATION), Matchers.eq(iid),
                Matchers.any(CapableSwitch.class), Matchers.eq(false));

        CheckedFuture checkedFuture = mock(CheckedFuture.class);

        when(wtx.submit()).thenReturn(checkedFuture);

        when(checkedFuture.checkedGet()).thenReturn(null);

        DataBroker mountDataBroker = mock(DataBroker.class);
        when(mountDataBroker.newReadOnlyTransaction()).thenReturn(rtx);

        when(mountDataBroker.newWriteOnlyTransaction()).thenReturn(wtx);

        MountPoint mountPoint = mock(MountPoint.class);
        when(mountPoint.getService(DataBroker.class)).thenReturn(Optional.of(mountDataBroker));

        when(mountService.getMountPoint(
                OfconfigConstants.NETCONF_TOPO_IID.child(Node.class, new NodeKey(new NodeId(netconfNodeId)))))
                        .thenReturn(Optional.of(mountPoint));

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.opendaylight.alto.basic.impl.AltoModelConfigImpl.java

protected QueryOutput readResourceNetworkMap(String rid, final ReadTransaction rx) {
    InstanceIdentifier<ResourceNetworkMap> iid = ManualMapsUtils.getResourceNetworkMapIID(rid);
    CheckedFuture<Optional<ResourceNetworkMap>, ReadFailedException> future = rx
            .read(LogicalDatastoreType.OPERATIONAL, iid);
    Optional<ResourceNetworkMap> optional = Optional.absent();

    QueryOutputBuilder outputBuilder = new QueryOutputBuilder();
    outputBuilder.setType(ResourceTypeConfig.class);
    ConfigResponseBuilder crBuilder = new ConfigResponseBuilder();
    ConfigResponseMessageBuilder crmBuilder = new ConfigResponseMessageBuilder();
    ConfigResponseData1Builder crdBuilder = new ConfigResponseData1Builder();

    ResourceNetworkMap result = null;/*ww  w .  j av a  2  s .c om*/
    String errorCode = RESPONSE_ERROR_CODE_FAILED;

    try {
        optional = future.checkedGet();
        if (optional.isPresent()) {
            result = optional.get();
            crdBuilder.setConfigNetworkmapResponseData(
                    new ConfigNetworkmapResponseDataBuilder().setResourceId(result.getResourceId())
                            .setTag(result.getTag()).setMap(result.getMap()).build());
            errorCode = RESPONSE_ERROR_CODE_OK;
        }
    } catch (Exception e) {
        LOG.warn("Reading resource failed! ResourceId: " + rid);
    }
    crmBuilder.setMeta((Meta) new Meta1Builder().setConfigResponseErrorCode(errorCode).build())
            .setConfigResponseData((ConfigResponseData) crdBuilder.build());
    crBuilder.setConfigResponseMessage(crmBuilder.build());
    outputBuilder.setResponse(crBuilder.build());
    return outputBuilder.build();
}

From source file:org.opendaylight.proxyarp.ProxyArp.java

public NodeConnector getNodeConnectorFromIID(InstanceIdentifier<NodeConnector> nodeConnectorIID) {
    ReadOnlyTransaction rtx = dataBroker.newReadOnlyTransaction();
    CheckedFuture<Optional<NodeConnector>, ReadFailedException> future = rtx
            .read(LogicalDatastoreType.OPERATIONAL, nodeConnectorIID);

    Optional<NodeConnector> optional = Optional.absent();
    try {// www.j a va2  s.co m
        optional = future.checkedGet();
        if (optional.isPresent()) {
            return optional.get();
        }
    } catch (ReadFailedException ex) {
        LOG.info("node connector not found for nodeconnector IID : {}", nodeConnectorIID);
    }

    LOG.info("node connector not found : {}", nodeConnectorIID);
    return null;
}