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.netconf.mdsal.connector.ops.RuntimeRpc.java

@Override
protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
        throws DocumentedException {

    final String netconfOperationName = operationElement.getName();
    final String netconfOperationNamespace;
    try {/*from   www.  j  a  v  a  2  s.  com*/
        netconfOperationNamespace = operationElement.getNamespace();
    } catch (DocumentedException e) {
        LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
        throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
                ErrorType.protocol, ErrorTag.unknown_namespace, ErrorSeverity.error);
    }

    final URI namespaceURI = createNsUri(netconfOperationNamespace);
    final Optional<Module> moduleOptional = getModule(namespaceURI);

    if (!moduleOptional.isPresent()) {
        throw new DocumentedException(
                "Unable to find module in Schema Context with namespace and name : " + namespaceURI + " "
                        + netconfOperationName + schemaContext.getCurrentContext(),
                ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
    }

    final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
            namespaceURI, netconfOperationName);

    if (!rpcDefinitionOptional.isPresent()) {
        throw new DocumentedException(
                "Unable to find RpcDefinition with namespace and name : " + namespaceURI + " "
                        + netconfOperationName,
                ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
    }

    final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
    final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
    final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());

    final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
    try {
        final DOMRpcResult result = rpcFuture.checkedGet();
        if (result.getResult() == null) {
            return XmlUtil.createElement(document, XmlNetconfConstants.OK,
                    Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
        }
        return (Element) transformNormalizedNode(document, result.getResult(),
                rpcDefinition.getOutput().getPath());
    } catch (DOMRpcException e) {
        throw DocumentedException.wrap(e);
    }
}

From source file:org.opendaylight.controller.netconf.mdsal.connector.ops.RuntimeRpc.java

@Override
protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
        throws NetconfDocumentedException {

    final String netconfOperationName = operationElement.getName();
    final String netconfOperationNamespace;
    try {/*from  w w  w  .java2s  . c o  m*/
        netconfOperationNamespace = operationElement.getNamespace();
    } catch (MissingNameSpaceException e) {
        LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
        throw new NetconfDocumentedException("Cannot retrieve netconf operation namespace from message",
                ErrorType.protocol, ErrorTag.unknown_namespace, ErrorSeverity.error);
    }

    final URI namespaceURI = createNsUri(netconfOperationNamespace);
    final Optional<Module> moduleOptional = getModule(namespaceURI);

    if (!moduleOptional.isPresent()) {
        throw new NetconfDocumentedException(
                "Unable to find module in Schema Context with namespace and name : " + namespaceURI + " "
                        + netconfOperationName + schemaContext.getCurrentContext(),
                ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
    }

    final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
            namespaceURI, netconfOperationName);

    if (!rpcDefinitionOptional.isPresent()) {
        throw new NetconfDocumentedException(
                "Unable to find RpcDefinition with namespace and name : " + namespaceURI + " "
                        + netconfOperationName,
                ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
    }

    final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
    final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
    final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());

    final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
    try {
        final DOMRpcResult result = rpcFuture.checkedGet();
        if (result.getResult() == null) {
            return XmlUtil.createElement(document, XmlNetconfConstants.OK,
                    Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
        }
        return (Element) transformNormalizedNode(document, result.getResult(),
                rpcDefinition.getOutput().getPath());
    } catch (DOMRpcException e) {
        throw NetconfDocumentedException.wrap(e);
    }
}

From source file:org.opendaylight.aaa.authn.mdsal.store.AuthNStore.java

private TokenList readTokenListFromDS(String userId) {
    InstanceIdentifier<TokenList> tokenList_iid = InstanceIdentifier.builder(TokenCacheTimes.class)
            .child(TokenList.class, new TokenListKey(userId)).build();
    TokenList tokenList = null;/*from  w  w  w.ja v a 2s .co m*/
    ReadTransaction rt = broker.newReadOnlyTransaction();
    CheckedFuture<Optional<TokenList>, ReadFailedException> userTokenListFuture = rt
            .read(LogicalDatastoreType.OPERATIONAL, tokenList_iid);
    try {
        Optional<TokenList> maybeTokenList = userTokenListFuture.checkedGet();
        if (maybeTokenList.isPresent()) {
            tokenList = maybeTokenList.get();
        }
    } catch (ReadFailedException e) {
        LOG.error("Something wrong happened in DataStore. Getting TokenList for userId {} failed.", userId, e);
    }
    return tokenList;
}

From source file:org.opendaylight.aaa.authn.mdsal.store.AuthNStore.java

private UserTokens readUserTokensFromDS(String token, String userId) {
    final InstanceIdentifier<UserTokens> userTokens_iid = AuthNStoreUtil.createInstIdentifierUserTokens(userId,
            token);/*from  www  . j  a  va  2s  .  c om*/
    UserTokens userTokens = null;

    ReadTransaction rt = broker.newReadOnlyTransaction();
    CheckedFuture<Optional<UserTokens>, ReadFailedException> userTokensFuture = rt
            .read(LogicalDatastoreType.OPERATIONAL, userTokens_iid);

    try {
        Optional<UserTokens> maybeUserTokens = userTokensFuture.checkedGet();
        if (maybeUserTokens.isPresent()) {
            userTokens = maybeUserTokens.get();
        }
    } catch (ReadFailedException e) {
        LOG.error("Something wrong happened in DataStore. Getting UserTokens for token {} failed.", token, e);
    }

    return userTokens;
}

From source file:org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver.java

/**
 * Try to parse all currently available yang files and build new schema context
 * in dependence on specified parsing mode.
 *
 * @param statementParserMode mode of statement parser
 * @return new schema context iif there is at least 1 yang file registered and
 *         new schema context was successfully built.
 *///from  ww  w  .  j a  va 2s  .  c o m
public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
    final SchemaContextFactory factory = repository
            .createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
    Optional<SchemaContext> sc;
    Object v;
    do {
        // Spin get stable context version
        Object cv;
        do {
            cv = contextVersion;
            sc = currentSchemaContext.get();
            if (version == cv) {
                return sc;
            }
        } while (cv != contextVersion);

        // Version has been updated
        Collection<SourceIdentifier> sources;
        do {
            v = version;
            sources = ImmutableSet.copyOf(requiredSources);
        } while (v != version);

        while (true) {
            final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory
                    .createSchemaContext(sources, statementParserMode);
            try {
                sc = Optional.of(f.checkedGet());
                break;
            } catch (SchemaResolutionException e) {
                LOG.info("Failed to fully assemble schema context for {}", sources, e);
                sources = e.getResolvedSources();
            }
        }

        LOG.debug("Resolved schema context for {}", sources);

        synchronized (this) {
            if (contextVersion == cv) {
                currentSchemaContext.set(sc);
                contextVersion = v;
            }
        }
    } while (version == v);

    return sc;
}

From source file:org.opendaylight.sfc.sfc_ios_xe.provider.utils.IosXeDataStoreAPI.java

private <U extends DataObject> U readTransaction(InstanceIdentifier<U> readIID) {
    long timeout = 5000L;
    int attempt = 0;
    ReadTransaction transaction = null;/*from  w  w w. j a v  a 2 s  .  co  m*/
    do {
        attempt++;
        try {
            transaction = mountpoint.newReadOnlyTransaction();
        } catch (RuntimeException e) {
            if (e.getCause().getClass().equals(NetconfDocumentedException.class)) {
                LOG.warn("NetconfDocumentedException thrown, retrying ({})...", attempt);
                try {
                    Thread.sleep(timeout);
                    timeout += 1000L;
                } catch (InterruptedException i) {
                    LOG.error("Thread interrupted while waiting ... {} ", i);
                }
            } else {
                LOG.error("Runtime exception ... {}", e.getMessage());
            }
        }
    } while (attempt <= 5 && transaction == null);
    if (transaction == null) {
        LOG.error("Maximum number of attempts reached");
        return null;
    }
    try {
        CheckedFuture<Optional<U>, ReadFailedException> submitFuture = transaction
                .read(Preconditions.checkNotNull(datastoreType), readIID);
        Optional<U> optional = submitFuture.checkedGet();
        if (optional != null && optional.isPresent()) {
            return optional.get();
        } else {
            LOG.debug("Failed to read. {}", Thread.currentThread().getStackTrace()[1]);
        }
    } catch (ReadFailedException e) {
        LOG.warn("Read transaction failed to {} ", e);
    } catch (Exception e) {
        LOG.error("Failed to .. {}", e.getMessage());
    }
    return null;
}

From source file:org.opendaylight.sfc.iosxe.provider.utils.IosXeDataStoreAPI.java

@SuppressWarnings("checkstyle:IllegalCatch")
private <U extends DataObject> U readTransaction(InstanceIdentifier<U> readIID) {
    long timeout = 5000L;
    int attempt = 0;
    ReadTransaction transaction = null;//from   w  w  w.j a v a2  s. c  o m
    do {
        attempt++;
        try {
            transaction = mountpoint.newReadOnlyTransaction();
        } catch (RuntimeException e) {
            if (e.getCause().getClass().equals(NetconfDocumentedException.class)) {
                LOG.warn("NetconfDocumentedException thrown, retrying ({})...", attempt);
                try {
                    Thread.sleep(timeout);
                    timeout += 1000L;
                } catch (InterruptedException i) {
                    LOG.error("Thread interrupted while waiting ... {} ", i);
                }
            } else {
                LOG.error("Runtime exception ... {}", e.getMessage());
            }
        }
    } while (attempt <= 5 && transaction == null);
    if (transaction == null) {
        LOG.error("Maximum number of attempts reached");
        return null;
    }
    try {
        CheckedFuture<Optional<U>, ReadFailedException> submitFuture = transaction
                .read(Preconditions.checkNotNull(datastoreType), readIID);
        Optional<U> optional = submitFuture.checkedGet();
        if (optional != null && optional.isPresent()) {
            return optional.get();
        } else {
            LOG.debug("Failed to read. {}", Thread.currentThread().getStackTrace()[1]);
        }
    } catch (ReadFailedException e) {
        LOG.warn("Read transaction failed to {} ", e);
    } catch (Exception e) {
        LOG.error("Failed to .. {}", e.getMessage());
    }
    return null;
}

From source file:org.opendaylight.nic.common.transaction.utils.CommonUtils.java

public void removeDataFlow(final String dataflowId) throws RemoveDataflowException {
    final InstanceIdentifier<Dataflow> identifier = InstanceIdentifier.create(Dataflows.class)
            .child(Dataflow.class, new DataflowKey(Uuid.getDefaultInstance(dataflowId)));
    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
    transaction.delete(LogicalDatastoreType.CONFIGURATION, identifier);
    CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = transaction.submit();
    try {/* www  .  j  a  v  a2 s.c o m*/
        checkedFuture.checkedGet();
    } catch (TransactionCommitFailedException e) {
        throw new RemoveDataflowException(e.getMessage());
    }
}

From source file:org.opendaylight.nic.common.transaction.utils.CommonUtils.java

public void removeDelayConfig(final String delayConfigId) throws RemoveDelayconfigException {
    final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
    final InstanceIdentifier<DelayConfig> identifier = InstanceIdentifier.create(DelayConfigs.class)
            .child(DelayConfig.class, new DelayConfigKey(Uuid.getDefaultInstance(delayConfigId)));
    writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, identifier);
    CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = writeTransaction.submit();
    try {//  w w  w. j  av a  2 s  .  co  m
        checkedFuture.checkedGet();
    } catch (TransactionCommitFailedException e) {
        throw new RemoveDelayconfigException(e.getMessage());
    }
}

From source file:org.opendaylight.nic.common.transaction.utils.CommonUtils.java

public void saveDataflow(final Dataflow dataflow) throws PushDataflowException {
    List<Dataflow> dataflows = retrieveDataflowList();
    final DataflowsBuilder dataflowsBuilder = new DataflowsBuilder();
    dataflows.add(dataflow);//from   w w  w . j a v  a  2 s.c om
    dataflowsBuilder.setDataflow(dataflows);
    final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
    writeTransaction.put(LogicalDatastoreType.CONFIGURATION, DATAFLOW_IID, dataflowsBuilder.build());
    CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = writeTransaction.submit();
    try {
        checkedFuture.checkedGet();
    } catch (TransactionCommitFailedException e) {
        LOG.error(e.getMessage());
        throw new PushDataflowException(e.getMessage());
    }
}