Search in sources :

Example 16 with XMLNamespace

use of org.opendaylight.yangtools.yang.common.XMLNamespace in project netconf by opendaylight.

the class RestconfDocumentedExceptionMapper method toJsonResponseBody.

private static Object toJsonResponseBody(final NormalizedNodeContext errorsNode, final DataNodeContainer errorsSchemaNode) {
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    NormalizedNode data = errorsNode.getData();
    final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
    final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
    final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
    if (data == null) {
        throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
    }
    boolean isDataRoot = false;
    XMLNamespace initialNs = null;
    SchemaPath path;
    if (context.getSchemaNode() instanceof SchemaContext) {
        isDataRoot = true;
        path = SchemaPath.ROOT;
    } else {
        final List<QName> qNames = context.getInstanceIdentifier().getPathArguments().stream().filter(arg -> !(arg instanceof NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof AugmentationIdentifier)).map(PathArgument::getNodeType).collect(Collectors.toList());
        path = SchemaPath.of(Absolute.of(qNames)).getParent();
    }
    if (!schema.isAugmenting() && !(schema instanceof SchemaContext)) {
        initialNs = schema.getQName().getNamespace();
    }
    final JsonWriter jsonWriter = JsonWriterFactory.createJsonWriter(outputWriter);
    final NormalizedNodeStreamWriter jsonStreamWriter = JSONNormalizedNodeStreamWriter.createExclusiveWriter(JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(context.getSchemaContext()), path, initialNs, jsonWriter);
    // We create a delegating writer to special-case error-info as error-info is defined as an empty
    // container in the restconf yang schema but we create a leaf node so we can output it. The delegate
    // stream writer validates the node type against the schema and thus will expect a LeafSchemaNode but
    // the schema has a ContainerSchemaNode so, to avoid an error, we override the leafNode behavior
    // for error-info.
    final NormalizedNodeStreamWriter streamWriter = new ForwardingNormalizedNodeStreamWriter() {

        private boolean inOurLeaf;

        @Override
        protected NormalizedNodeStreamWriter delegate() {
            return jsonStreamWriter;
        }

        @Override
        public void startLeafNode(final NodeIdentifier name) throws IOException {
            if (name.getNodeType().equals(RestConfModule.ERROR_INFO_QNAME)) {
                inOurLeaf = true;
                jsonWriter.name(RestConfModule.ERROR_INFO_QNAME.getLocalName());
            } else {
                super.startLeafNode(name);
            }
        }

        @Override
        public void scalarValue(final Object value) throws IOException {
            if (inOurLeaf) {
                jsonWriter.value(value.toString());
            } else {
                super.scalarValue(value);
            }
        }

        @Override
        public void endNode() throws IOException {
            if (inOurLeaf) {
                inOurLeaf = false;
            } else {
                super.endNode();
            }
        }
    };
    final NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter);
    try {
        if (isDataRoot) {
            writeDataRoot(outputWriter, nnWriter, (ContainerNode) data);
        } else {
            if (data instanceof MapEntryNode) {
                data = ImmutableNodes.mapNodeBuilder(data.getIdentifier().getNodeType()).withChild((MapEntryNode) data).build();
            }
            nnWriter.write(data);
        }
        nnWriter.flush();
        outputWriter.flush();
    } catch (final IOException e) {
        LOG.warn("Error writing error response body", e);
    }
    try {
        streamWriter.close();
    } catch (IOException e) {
        LOG.warn("Failed to close stream writer", e);
    }
    return outStream.toString(StandardCharsets.UTF_8);
}
Also used : JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) JSONCodecFactorySupplier(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier) Provider(javax.ws.rs.ext.Provider) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) LoggerFactory(org.slf4j.LoggerFactory) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ERRORS_CONTAINER_QNAME(org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule.ERRORS_CONTAINER_QNAME) MediaType(javax.ws.rs.core.MediaType) NormalizedNodeWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter) XMLStreamException(javax.xml.stream.XMLStreamException) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) CollectionNodeBuilder(org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder) Context(javax.ws.rs.core.Context) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) DataContainerChild(org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ErrorTags(org.opendaylight.restconf.common.ErrorTags) XMLStreamNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) PathArgument(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument) ImmutableNodes(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) Iterables(com.google.common.collect.Iterables) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) ArrayList(java.util.ArrayList) RestConfModule(org.opendaylight.netconf.sal.rest.api.Draft02.RestConfModule) JsonWriterFactory(org.opendaylight.yangtools.yang.data.codec.gson.JsonWriterFactory) Objects.requireNonNull(java.util.Objects.requireNonNull) OutputStreamWriter(java.io.OutputStreamWriter) SystemMapNode(org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode) XMLConstants(javax.xml.XMLConstants) JsonWriter(com.google.gson.stream.JsonWriter) Status(javax.ws.rs.core.Response.Status) SchemaAwareBuilders(org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders) Logger(org.slf4j.Logger) DataContainerNodeBuilder(org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) RestconfError(org.opendaylight.restconf.common.errors.RestconfError) QName(org.opendaylight.yangtools.yang.common.QName) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) DataNodeContainer(org.opendaylight.yangtools.yang.model.api.DataNodeContainer) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) ControllerContext(org.opendaylight.netconf.sal.restconf.impl.ControllerContext) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) AugmentationIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) LeafSchemaNode(org.opendaylight.yangtools.yang.model.api.LeafSchemaNode) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) AugmentationIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) NormalizedNodeWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter) QName(org.opendaylight.yangtools.yang.common.QName) JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) XMLStreamNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) JsonWriter(com.google.gson.stream.JsonWriter) SchemaPath(org.opendaylight.yangtools.yang.model.api.SchemaPath) NodeIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) ForwardingNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.ForwardingNormalizedNodeStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)

Example 17 with XMLNamespace

use of org.opendaylight.yangtools.yang.common.XMLNamespace in project netconf by opendaylight.

the class NormalizedNodeJsonBodyWriter method createNormalizedNodeWriter.

private static RestconfNormalizedNodeWriter createNormalizedNodeWriter(final InstanceIdentifierContext<SchemaNode> context, final SchemaPath path, final JsonWriter jsonWriter, @Nullable final Integer depth) {
    final SchemaNode schema = context.getSchemaNode();
    final JSONCodecFactory codecs = getCodecFactory(context);
    final XMLNamespace initialNs;
    if (schema instanceof DataSchemaNode && !((DataSchemaNode) schema).isAugmenting() && !(schema instanceof SchemaContext) || schema instanceof RpcDefinition) {
        initialNs = schema.getQName().getNamespace();
    } else {
        initialNs = null;
    }
    final NormalizedNodeStreamWriter streamWriter = JSONNormalizedNodeStreamWriter.createNestedWriter(codecs, path, initialNs, jsonWriter);
    if (depth != null) {
        return DepthAwareNormalizedNodeWriter.forStreamWriter(streamWriter, depth);
    }
    return RestconfDelegatingNormalizedNodeWriter.forStreamWriter(streamWriter);
}
Also used : SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) RpcDefinition(org.opendaylight.yangtools.yang.model.api.RpcDefinition) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) JSONCodecFactory(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) JSONNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) SchemaContext(org.opendaylight.yangtools.yang.model.api.SchemaContext)

Example 18 with XMLNamespace

use of org.opendaylight.yangtools.yang.common.XMLNamespace in project netconf by opendaylight.

the class RuntimeRpc method handleWithNoSubsequentOperations.

@Override
protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
    final String netconfOperationName = operationElement.getName();
    final String netconfOperationNamespace;
    try {
        netconfOperationNamespace = operationElement.getNamespace();
    } catch (final DocumentedException e) {
        LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
        throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
    }
    final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
    final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
    if (moduleOptional.isEmpty()) {
        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.isEmpty()) {
        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 ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
    final DOMRpcResult result;
    try {
        result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
    } catch (final InterruptedException | ExecutionException e) {
        throw DocumentedException.wrap(e);
    }
    if (result.getResult() == null) {
        return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
    }
    return transformNormalizedNode(document, result.getResult(), Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName()));
}
Also used : RpcDefinition(org.opendaylight.yangtools.yang.model.api.RpcDefinition) DOMRpcResult(org.opendaylight.mdsal.dom.api.DOMRpcResult) NetconfDocumentedException(org.opendaylight.netconf.api.NetconfDocumentedException) DocumentedException(org.opendaylight.netconf.api.DocumentedException) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) ContainerNode(org.opendaylight.yangtools.yang.data.api.schema.ContainerNode) ExecutionException(java.util.concurrent.ExecutionException)

Example 19 with XMLNamespace

use of org.opendaylight.yangtools.yang.common.XMLNamespace in project netconf by opendaylight.

the class RestDocgenUtil method resolveFullNameFromNode.

private static String resolveFullNameFromNode(final QName node, final SchemaContext schemaContext) {
    final XMLNamespace namespace = node.getNamespace();
    final Optional<Revision> revision = node.getRevision();
    final Map<Optional<Revision>, Module> revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.computeIfAbsent(namespace, k -> new HashMap<>());
    final Module module = revisionToModule.computeIfAbsent(revision, k -> schemaContext.findModule(namespace, k).orElse(null));
    if (module != null) {
        return module.getName() + ":" + node.getLocalName();
    }
    return node.getLocalName();
}
Also used : Revision(org.opendaylight.yangtools.yang.common.Revision) Optional(java.util.Optional) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) Module(org.opendaylight.yangtools.yang.model.api.Module)

Example 20 with XMLNamespace

use of org.opendaylight.yangtools.yang.common.XMLNamespace in project controller by opendaylight.

the class ConfigurationImplTest method testAddModuleShardConfiguration.

@Test
public void testAddModuleShardConfiguration() throws Exception {
    XMLNamespace namespace = XMLNamespace.of("urn:opendaylight:test:oven");
    String moduleName = "oven";
    String shardName = "oven-shard";
    String shardStrategyName = ModuleShardStrategy.NAME;
    Collection<MemberName> shardMemberNames = ImmutableSortedSet.of(MEMBER_1, MEMBER_4, MEMBER_5);
    configuration.addModuleShardConfiguration(new ModuleShardConfiguration(namespace, moduleName, shardName, shardStrategyName, shardMemberNames));
    assertEquals("getMemberShardNames", ImmutableSortedSet.of("people-1", "cars-1", "test-1", "default", shardName), ImmutableSortedSet.copyOf(configuration.getMemberShardNames(MEMBER_1)));
    assertEquals("getMemberShardNames", ImmutableSortedSet.of(shardName), ImmutableSortedSet.copyOf(configuration.getMemberShardNames(MEMBER_4)));
    assertEquals("getMemberShardNames", ImmutableSortedSet.of(shardName), ImmutableSortedSet.copyOf(configuration.getMemberShardNames(MEMBER_5)));
    assertEquals("getMembersFromShardName", shardMemberNames, ImmutableSortedSet.copyOf(configuration.getMembersFromShardName(shardName)));
    assertEquals("getShardNameForModule", shardName, configuration.getShardNameForModule(moduleName));
    assertEquals("getModuleNameFromNameSpace", moduleName, configuration.getModuleNameFromNameSpace(namespace.toString()));
    assertEquals("getAllShardNames", ImmutableSortedSet.of("people-1", "cars-1", "test-1", "default", shardName), ImmutableSortedSet.copyOf(configuration.getAllShardNames()));
    ShardStrategy strategy = configuration.getStrategyForModule("cars");
    assertNotNull("getStrategyForModule null", strategy);
    assertEquals("getStrategyForModule type", ModuleShardStrategy.class, strategy.getClass());
}
Also used : ShardStrategy(org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy) ModuleShardStrategy(org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) MemberName(org.opendaylight.controller.cluster.access.concepts.MemberName) Test(org.junit.Test)

Aggregations

XMLNamespace (org.opendaylight.yangtools.yang.common.XMLNamespace)35 Module (org.opendaylight.yangtools.yang.model.api.Module)14 QName (org.opendaylight.yangtools.yang.common.QName)12 QNameModule (org.opendaylight.yangtools.yang.common.QNameModule)9 Revision (org.opendaylight.yangtools.yang.common.Revision)9 DataSchemaNode (org.opendaylight.yangtools.yang.model.api.DataSchemaNode)9 Test (org.junit.Test)8 LeafSchemaNode (org.opendaylight.yangtools.yang.model.api.LeafSchemaNode)4 RpcDefinition (org.opendaylight.yangtools.yang.model.api.RpcDefinition)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 ContainerNode (org.opendaylight.yangtools.yang.data.api.schema.ContainerNode)3 ContainerSchemaNode (org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode)3 EffectiveModelContext (org.opendaylight.yangtools.yang.model.api.EffectiveModelContext)3 ListSchemaNode (org.opendaylight.yangtools.yang.model.api.ListSchemaNode)3 ModuleImport (org.opendaylight.yangtools.yang.model.api.ModuleImport)3 SchemaContext (org.opendaylight.yangtools.yang.model.api.SchemaContext)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 SimpleImmutableEntry (java.util.AbstractMap.SimpleImmutableEntry)2 Optional (java.util.Optional)2