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.controller.config.facade.xml.osgi.YangStoreSnapshot.java

@Override
public String getModuleSource(
        final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
    final CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> source = sourceProvider
            .getSource(SourceIdentifier.create(moduleIdentifier.getName(),
                    Optional.fromNullable(QName.formattedRevision(moduleIdentifier.getRevision()))));

    try {//from  w ww .  j a v  a  2 s .com
        final YangTextSchemaSource yangTextSchemaSource = source.checkedGet();
        try (InputStream inStream = yangTextSchemaSource.openStream()) {
            return new String(ByteStreams.toByteArray(inStream), StandardCharsets.UTF_8);
        }
    } catch (SchemaSourceException | IOException e) {
        LOG.warn("Unable to provide source for {}", moduleIdentifier, e);
        throw new IllegalArgumentException("Unable to provide source for " + moduleIdentifier, e);
    }
}

From source file:com.cisco.devnetlabs.choochoo.impl.ChoochooTrainManager.java

private Train readTrain(String locoId, LogicalDatastoreType ldsType) {

    ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();

    InstanceIdentifier<Train> iid = InstanceIdentifier.create(TrainTopology.class).child(Train.class,
            new TrainKey(locoId));

    Train train = null;//from  w  ww.  j  a  va2s . c  o  m

    Optional<Train> optionalDataObject;
    CheckedFuture<Optional<Train>, ReadFailedException> submitFuture = tx.read(ldsType, iid);
    try {
        optionalDataObject = submitFuture.checkedGet();
        if (optionalDataObject != null && optionalDataObject.isPresent()) {
            train = optionalDataObject.get();
        }
    } catch (ReadFailedException e) {
        LOG.error("failed to ....", e);
    }

    LOG.info("read: train: {}", locoId);

    return train;
}

From source file:com.google.gerrit.server.change.Publish.java

@Override
public Response<?> apply(RevisionResource rsrc, Input input)
        throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException, IOException {
    if (!rsrc.getPatchSet().isDraft()) {
        throw new ResourceConflictException("Patch set is not a draft");
    }// w w  w  .  j av a2 s . c om

    if (!rsrc.getControl().canPublish(dbProvider.get())) {
        throw new AuthException("Cannot publish this draft patch set");
    }

    if (!allowDrafts) {
        throw new ResourceConflictException("Draft workflow is disabled.");
    }

    PatchSet updatedPatchSet = updateDraftPatchSet(rsrc);
    Change updatedChange = updateDraftChange(rsrc);
    ChangeUpdate update = updateFactory.create(rsrc.getControl(), updatedChange.getLastUpdatedOn());

    try {
        if (!updatedPatchSet.isDraft() || updatedChange.getStatus() == Change.Status.NEW) {
            CheckedFuture<?, IOException> indexFuture = indexer.indexAsync(updatedChange.getId());
            hooks.doDraftPublishedHook(updatedChange, updatedPatchSet, dbProvider.get());
            sender.send(rsrc.getNotes(), update, rsrc.getChange().getStatus() == Change.Status.DRAFT,
                    rsrc.getUser(), updatedChange, updatedPatchSet, rsrc.getControl().getLabelTypes());
            indexFuture.checkedGet();
        }
    } catch (PatchSetInfoNotAvailableException e) {
        throw new ResourceNotFoundException(e.getMessage());
    }

    return Response.none();
}

From source file:com.cisco.devnetlabs.choochoo.impl.ChoochooTrainManager.java

private TrainTopology readTrainTopology(LogicalDatastoreType ldsType) {

    ReadWriteTransaction tx = dataBroker.newReadWriteTransaction();

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

    TrainTopology tt = null;/* w w  w.j  a  v  a  2s  .  c  o m*/

    Optional<TrainTopology> optionalDataObject;
    CheckedFuture<Optional<TrainTopology>, ReadFailedException> submitFuture = tx.read(ldsType, iid);
    try {
        optionalDataObject = submitFuture.checkedGet();
        if (optionalDataObject != null && optionalDataObject.isPresent()) {
            tt = optionalDataObject.get();
        }
    } catch (ReadFailedException e) {
        LOG.error("failed to ....", e);
    }

    LOG.info("read: traintopology");

    return tt;
}

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

protected <T extends org.opendaylight.yangtools.yang.binding.DataObject> T readMemberMd(
        InstanceIdentifier<T> path) {
    T result = null;/*from  ww  w.ja v a  2  s.  co m*/
    final ReadOnlyTransaction transaction = getDataBroker().newReadOnlyTransaction();
    final CheckedFuture<Optional<T>, ReadFailedException> future = transaction
            .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);
        }
    }
    transaction.close();
    return result;
}

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

private void deleteFederatedNetFromConfigDs(String netId) {
    LOG.info("deleteFederatedNetFromConfigDs {}", netId);
    WriteTransaction deleteTx = db.newWriteOnlyTransaction();
    InstanceIdentifier<FederatedNetwork> netPath = InstanceIdentifier.create(FederatedNetworks.class)
            .child(FederatedNetwork.class, new FederatedNetworkKey(netId));
    deleteTx.delete(LogicalDatastoreType.CONFIGURATION, netPath);
    CheckedFuture<Void, TransactionCommitFailedException> future1 = deleteTx.submit();
    try {/*  w w  w  .j ava  2 s  .c  o m*/
        future1.checkedGet();
    } catch (org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException e) {
        LOG.error("deleteFederatedNetFromConfigDs - Failed to delete network " + e.getMessage(), e);
    }
}

From source file:org.opendaylight.tsdr.syslogs.server.datastore.SyslogDatastoreManager.java

@Override
public Future<RpcResult<ShowRegisterFilterOutput>> showRegisterFilter() {

    ReadTransaction transaction = db.newReadOnlyTransaction();
    InstanceIdentifier<SyslogDispatcher> iid = InstanceIdentifier.create(SyslogDispatcher.class);
    CheckedFuture<Optional<SyslogDispatcher>, ReadFailedException> future = transaction
            .read(LogicalDatastoreType.CONFIGURATION, iid);
    Optional<SyslogDispatcher> optional = Optional.absent();
    try {/* ww  w.  jav  a 2  s  . c  o m*/
        optional = future.checkedGet();
    } catch (ReadFailedException e) {
        LOG.warn("Reading Filter failed");
        ShowRegisterFilterOutput output = new ShowRegisterFilterOutputBuilder()
                .setResult("Reading Filter failed").build();
        return RpcResultBuilder.success(output).buildFuture();
    }
    if (optional.isPresent() && !(optional.get().getSyslogFilter().isEmpty())) {

        LOG.info("reading filter success");

        List<SyslogFilter> filters = optional.get().getSyslogFilter();
        LOG.info("currently registered filters are:     " + filters);
        List<RegisteredSyslogFilter> registeredSyslogFiltersList = new ArrayList<>();
        for (SyslogFilter filter : filters) {
            LOG.info("filter entity:  " + filter.getFilterEntity());
            LOG.info("filter ID:  " + filter.getFilterId());

            RegisteredFilterEntity registeredFilterEntity = new RegisteredFilterEntityBuilder()
                    .setApplication(filter.getFilterEntity().getApplication())
                    .setContent(filter.getFilterEntity().getContent())
                    .setFacility(filter.getFilterEntity().getFacility())
                    .setHost(filter.getFilterEntity().getHost()).setPid(filter.getFilterEntity().getPid())
                    .setSid(filter.getFilterEntity().getSid())
                    .setSeverity(filter.getFilterEntity().getSeverity()).build();

            RegisteredSyslogFilter filter1 = new RegisteredSyslogFilterBuilder()
                    .setFilterId(filter.getFilterId()).setRegisteredFilterEntity(registeredFilterEntity)
                    .setCallbackUrl(filter.getCallbackUrl()).build();
            registeredSyslogFiltersList.add(filter1);
        }
        ShowRegisterFilterOutput output = new ShowRegisterFilterOutputBuilder()
                .setResult("registered filters are:").setRegisteredSyslogFilter(registeredSyslogFiltersList)
                .build();

        return RpcResultBuilder.success(output).buildFuture();
    } else {
        ShowRegisterFilterOutput output = new ShowRegisterFilterOutputBuilder()
                .setResult("no registered filter").build();
        return RpcResultBuilder.success(output).buildFuture();
    }
}

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

private boolean writeNewConfig(UpdateFederatedNetworksInput input) {
    if (input.getFederatedNetworksIn() == null) {
        LOG.info("writeNewConfig - no networks in input!");
        return false;
    }/*from ww w .  jav a 2s.c o m*/
    LOG.debug("writeNewConfig");
    WriteTransaction putTx = db.newWriteOnlyTransaction();
    List<FederatedNetworksIn> newFederatedNetworks = input.getFederatedNetworksIn();
    for (FederatedNetworksIn net : newFederatedNetworks) {
        FederatedNetwork netInConfig = getFederatedNetFromConfigDs(net.getSelfNetId());

        if (!isEqualFederatedNet(netInConfig, net)) {
            // network updates or new
            FederatedNetworkBuilder builder = new FederatedNetworkBuilder();
            builder.setSelfNetId(net.getSelfNetId());
            builder.setSelfSubnetId(net.getSelfSubnetId());
            builder.setSelfTenantId(net.getSelfTenantId());
            builder.setSiteNetwork(net.getSiteNetwork());
            InstanceIdentifier<FederatedNetwork> path = InstanceIdentifier.create(FederatedNetworks.class)
                    .child(FederatedNetwork.class, new FederatedNetworkKey(net.getSelfNetId()));
            FederatedNetwork newNet = builder.build();
            LOG.info("writeNewConfig add new federated network {}", newNet);
            putTx.put(LogicalDatastoreType.CONFIGURATION, path, newNet);
        }
    }
    List<FederatedAclsIn> newFederatedSecGroups = input.getFederatedAclsIn();
    for (FederatedAclsIn secGroup : newFederatedSecGroups) {
        FederatedAcl secInConfig = getFederatedAclFromConfigDs(secGroup.getKey().getSelfAclId());

        if (!isEqualAcl(secInConfig, secGroup)) {
            // group update or new group
            FederatedAclBuilder builder = new FederatedAclBuilder();
            builder.setSelfAclId(secGroup.getKey().getSelfAclId());
            builder.setSiteAcl(secGroup.getSiteAcl());
            KeyedInstanceIdentifier<FederatedAcl, FederatedAclKey> path = InstanceIdentifier
                    .create(FederatedAcls.class)
                    .child(FederatedAcl.class, new FederatedAclKey(secGroup.getKey().getSelfAclId()));
            FederatedAcl newSecGroup = builder.build();
            LOG.info("writeNewConfig add new federated security group {}", newSecGroup);
            putTx.put(LogicalDatastoreType.CONFIGURATION, path, newSecGroup);
        }
    }
    CheckedFuture<Void, TransactionCommitFailedException> future1 = putTx.submit();
    try {
        future1.checkedGet();
    } catch (TransactionCommitFailedException e) {
        LOG.error("updateFederatedNetworks - Failed to write new configuration " + e.getMessage(), e);
        return false;
    }
    return true;
}

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

/**
 * Start closed loop process. Read all possible devices from topology. Read airinterface name. Modify it on another name.
 * @return// w  ww . ja  v a  2s . co  m
  */
public boolean processNetworkDevices() {
    ReadWriteTransaction transaction = dataBroker.newReadWriteTransaction();
    CheckedFuture<Optional<Topology>, ReadFailedException> topology = transaction
            .read(LogicalDatastoreType.OPERATIONAL, NETCONF_TOPO_IID);

    try {
        Optional<Topology> optTopology = topology.checkedGet();
        List<Node> nodeList = optTopology.get().getNode();
        for (Node node : nodeList) { // loop all nodes from topology
            LOG.info("Node : {}", node.getKey().getNodeId());
            if (canProcessDevice(node)) { // check if we can process it
                processNode(node.getKey());
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider.java

@Override
public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
        final SourceIdentifier sourceIdentifier) {
    final String moduleName = sourceIdentifier.getName();

    // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
    final String formattedRevision = sourceIdentifier.getRevision()
            .equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) ? null : sourceIdentifier.getRevision();
    final Optional<String> revision = Optional.fromNullable(formattedRevision);
    final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);

    logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);

    final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
            rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
                    getSchemaRequest),/*from   w  ww.  ja  v  a  2  s.  c om*/
            new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));

    final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed,
            MAPPER);

    // / FIXME remove this get, it is only present to wait until source is retrieved
    // (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly)
    // TODO retest this
    try {
        logger.trace("{}: Blocking for {}", id, sourceIdentifier);
        checked.checkedGet();
    } catch (final SchemaSourceException e) {
        return Futures.immediateFailedCheckedFuture(e);
    }

    return checked;
}