Search in sources :

Example 1 with EffectiveStatement

use of org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement in project mdsal by opendaylight.

the class JavaFileTemplate method appendSnippet.

static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
    type.getYangSourceDefinition().ifPresent(def -> {
        sb.append('\n');
        if (def instanceof Single) {
            final DocumentedNode node = ((Single) def).getNode();
            sb.append("<p>\n").append("This class represents the following YANG schema fragment defined in module <b>").append(def.getModule().argument().getLocalName()).append("</b>\n").append("<pre>\n");
            appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
            sb.append("</pre>");
            if (node instanceof SchemaNode) {
                final SchemaNode schema = (SchemaNode) node;
                if (hasBuilderClass(schema)) {
                    final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
                    sb.append("\n<p>To create instances of this class use {@link ").append(builderName).append("}.\n").append("@see ").append(builderName).append('\n');
                    if (node instanceof ListSchemaNode) {
                        final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
                        if (!keyDef.isEmpty()) {
                            sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
                        }
                        sb.append('\n');
                    }
                }
            }
        } else if (def instanceof Multiple) {
            sb.append("<pre>\n");
            for (SchemaNode node : ((Multiple) def).getNodes()) {
                appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
            }
            sb.append("</pre>\n");
        }
    });
}
Also used : ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) Multiple(org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple) Single(org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single) ModuleEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement) EffectiveStatement(org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement) DocumentedNode(org.opendaylight.yangtools.yang.model.api.DocumentedNode) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode)

Example 2 with EffectiveStatement

use of org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement in project netconf by opendaylight.

the class XmlToPatchBodyReader method parse.

private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
    final List<PatchEntity> resultCollection = new ArrayList<>();
    final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
    final NodeList editNodes = doc.getElementsByTagName("edit");
    for (int i = 0; i < editNodes.getLength(); i++) {
        DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
        final Element element = (Element) editNodes.item(i);
        final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
        final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
        final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
        final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
        final List<Element> values = readValueNodes(element, oper);
        final Element firstValueElement = values != null ? values.get(0) : null;
        // get namespace according to schema node from path context or value
        final String namespace = firstValueElement == null ? schemaNode.getQName().getNamespace().toString() : firstValueElement.getNamespaceURI();
        // find module according to namespace
        final Module module = pathContext.getSchemaContext().findModules(XMLNamespace.of(namespace)).iterator().next();
        // initialize codec + set default prefix derived from module name
        final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(pathContext.getSchemaContext(), module.getName());
        // find complete path to target and target schema node
        // target can be also empty (only slash)
        YangInstanceIdentifier targetII;
        final SchemaNode targetNode;
        final Inference inference;
        if (target.equals("/")) {
            targetII = pathContext.getInstanceIdentifier();
            targetNode = pathContext.getSchemaContext();
            inference = Inference.ofDataTreePath(pathContext.getSchemaContext(), schemaNode.getQName());
        } else {
            targetII = codec.deserialize(codec.serialize(pathContext.getInstanceIdentifier()).concat(prepareNonCondXpath(schemaNode, target.replaceFirst("/", ""), firstValueElement, namespace, module.getQNameModule().getRevision().map(Revision::toString).orElse(null))));
            // move schema node
            schemaNode = verifyNotNull(codec.getDataContextTree().findChild(targetII).orElseThrow().getDataSchemaNode());
            final SchemaInferenceStack stack = SchemaInferenceStack.of(pathContext.getSchemaContext());
            targetII.getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
            final EffectiveStatement<?, ?> parentStmt = stack.exit();
            verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
            targetNode = (SchemaNode) parentStmt;
            inference = stack.toInference();
        }
        if (targetNode == null) {
            LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
            throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
        }
        if (oper.isWithValue()) {
            final NormalizedNode parsed;
            if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
                final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
                final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
                final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
                xmlParser.traverse(new DOMSource(firstValueElement));
                parsed = resultHolder.getResult();
            } else {
                parsed = null;
            }
            // for lists allow to manipulate with list items through their parent
            if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
                targetII = targetII.getParent();
            }
            resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
        } else {
            resultCollection.add(new PatchEntity(editId, oper, targetII));
        }
    }
    return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
}
Also used : SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) Provider(javax.ws.rs.ext.Provider) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) URISyntaxException(java.net.URISyntaxException) Draft02(org.opendaylight.netconf.sal.rest.api.Draft02) LoggerFactory(org.slf4j.LoggerFactory) UntrustedXML(org.opendaylight.yangtools.util.xml.UntrustedXML) XMLNamespace(org.opendaylight.yangtools.yang.common.XMLNamespace) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) Locale(java.util.Locale) Document(org.w3c.dom.Document) XMLStreamException(javax.xml.stream.XMLStreamException) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) RestconfService(org.opendaylight.netconf.sal.rest.api.RestconfService) Splitter(com.google.common.base.Splitter) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) Module(org.opendaylight.yangtools.yang.model.api.Module) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) Inference(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference) List(java.util.List) Revision(org.opendaylight.yangtools.yang.common.Revision) Type(java.lang.reflect.Type) SAXException(org.xml.sax.SAXException) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) NonNull(org.eclipse.jdt.annotation.NonNull) Verify.verifyNotNull(com.google.common.base.Verify.verifyNotNull) DOMSource(javax.xml.transform.dom.DOMSource) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) PatchEntity(org.opendaylight.restconf.common.patch.PatchEntity) ArrayList(java.util.ArrayList) ErrorType(org.opendaylight.yangtools.yang.common.ErrorType) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) XmlParserStream(org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream) Node(org.w3c.dom.Node) EffectiveStatement(org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement) RestUtil(org.opendaylight.restconf.common.util.RestUtil) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) Iterator(java.util.Iterator) SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) ErrorTag(org.opendaylight.yangtools.yang.common.ErrorTag) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) QName(org.opendaylight.yangtools.yang.common.QName) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Element(org.w3c.dom.Element) DataNodeContainer(org.opendaylight.yangtools.yang.model.api.DataNodeContainer) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) 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) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) PatchEditOperation(org.opendaylight.restconf.common.patch.PatchEditOperation) XmlParserStream(org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) DOMSource(javax.xml.transform.dom.DOMSource) PatchEntity(org.opendaylight.restconf.common.patch.PatchEntity) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) PatchEditOperation(org.opendaylight.restconf.common.patch.PatchEditOperation) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) NodeList(org.w3c.dom.NodeList) Inference(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) Module(org.opendaylight.yangtools.yang.model.api.Module) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates)

Example 3 with EffectiveStatement

use of org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement in project yangtools by opendaylight.

the class StatementPrefixResolver method forModule.

static StatementPrefixResolver forModule(final ModuleEffectiveStatement module) {
    final Map<QNameModule, String> imports = module.getAll(QNameModuleToPrefixNamespace.class);
    final Collection<SubmoduleEffectiveStatement> submodules = module.getAll(NameToEffectiveSubmoduleNamespace.class).values();
    if (submodules.isEmpty()) {
        // Simple: it's just the module
        return new StatementPrefixResolver(imports);
    }
    // Stage one: check what everyone thinks about imports
    final Map<String, Multimap<QNameModule, EffectiveStatement<?, ?>>> prefixToNamespaces = new HashMap<>();
    indexPrefixes(prefixToNamespaces, imports, module);
    for (SubmoduleEffectiveStatement submodule : submodules) {
        indexPrefixes(prefixToNamespaces, submodule.getAll(QNameModuleToPrefixNamespace.class), submodule);
    }
    // Stage two: see what QNameModule -> prefix mappings there are. We will need to understand this in step three
    final Multimap<QNameModule, String> namespaceToPrefixes = HashMultimap.create();
    for (Entry<String, Multimap<QNameModule, EffectiveStatement<?, ?>>> entry : prefixToNamespaces.entrySet()) {
        for (QNameModule namespace : entry.getValue().keySet()) {
            namespaceToPrefixes.put(namespace, entry.getKey());
        }
    }
    // Stage three: resolve first order of conflicts, potentially completely resolving mappings...
    final Builder<QNameModule, Object> builder = ImmutableMap.builderWithExpectedSize(prefixToNamespaces.size());
    // ... first resolve unambiguous mappings ...
    final Iterator<Entry<String, Multimap<QNameModule, EffectiveStatement<?, ?>>>> it = prefixToNamespaces.entrySet().iterator();
    while (it.hasNext()) {
        final Entry<String, Multimap<QNameModule, EffectiveStatement<?, ?>>> entry = it.next();
        final Multimap<QNameModule, EffectiveStatement<?, ?>> modules = entry.getValue();
        if (modules.size() == 1) {
            // Careful now: the namespace needs to be unambiguous
            final QNameModule namespace = modules.keys().iterator().next();
            if (namespaceToPrefixes.get(namespace).size() == 1) {
                builder.put(namespace, entry.getKey());
                it.remove();
            }
        }
    }
    // .. check for any remaining conflicts ...
    if (!prefixToNamespaces.isEmpty()) {
        final Multimap<QNameModule, Entry<DeclaredStatement<?>, String>> conflicts = ArrayListMultimap.create();
        for (Entry<String, Multimap<QNameModule, EffectiveStatement<?, ?>>> entry : prefixToNamespaces.entrySet()) {
            for (Entry<QNameModule, EffectiveStatement<?, ?>> namespace : entry.getValue().entries()) {
                conflicts.put(namespace.getKey(), new SimpleImmutableEntry<>(namespace.getValue().getDeclared(), entry.getKey()));
            }
        }
        builder.putAll(Maps.transformValues(conflicts.asMap(), Conflict::new));
    }
    return new StatementPrefixResolver(builder.build());
}
Also used : QNameModuleToPrefixNamespace(org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement.QNameModuleToPrefixNamespace) HashMap(java.util.HashMap) NameToEffectiveSubmoduleNamespace(org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement.NameToEffectiveSubmoduleNamespace) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Multimap(com.google.common.collect.Multimap) HashMultimap(com.google.common.collect.HashMultimap) SubmoduleEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) Entry(java.util.Map.Entry) ModuleEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement) EffectiveStatement(org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement) SubmoduleEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement) QNameModule(org.opendaylight.yangtools.yang.common.QNameModule)

Example 4 with EffectiveStatement

use of org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement in project netconf by opendaylight.

the class JsonNormalizedNodeBodyReader method readFrom.

public static NormalizedNodePayload readFrom(final InstanceIdentifierContext<?> path, final InputStream entityStream, final boolean isPost) {
    final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
    final EffectiveStatementInference parentSchema;
    final SchemaInferenceStack stack;
    if (path.getSchemaNode() instanceof RpcEffectiveStatement) {
        stack = SchemaInferenceStack.of(path.getSchemaContext(), Absolute.of(path.getSchemaNode().getQName()));
    } else {
        stack = SchemaInferenceStack.of(path.getSchemaContext());
        path.getInstanceIdentifier().getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
    }
    if (!isPost) {
        stack.exit();
    }
    parentSchema = stack.toInference();
    final JsonParserStream jsonParser = JsonParserStream.create(writer, JSONCodecFactorySupplier.RFC7951.getShared(path.getSchemaContext()), parentSchema);
    final JsonReader reader = new JsonReader(new InputStreamReader(entityStream, StandardCharsets.UTF_8));
    jsonParser.parse(reader);
    NormalizedNode result = resultHolder.getResult();
    final List<YangInstanceIdentifier.PathArgument> iiToDataList = new ArrayList<>();
    InstanceIdentifierContext<? extends SchemaNode> newIIContext;
    while (result instanceof AugmentationNode || result instanceof ChoiceNode) {
        final Object childNode = ((DataContainerNode) result).body().iterator().next();
        if (isPost) {
            iiToDataList.add(result.getIdentifier());
        }
        result = (NormalizedNode) childNode;
    }
    if (isPost) {
        if (result instanceof MapEntryNode) {
            iiToDataList.add(new YangInstanceIdentifier.NodeIdentifier(result.getIdentifier().getNodeType()));
            iiToDataList.add(result.getIdentifier());
        } else {
            final List<? extends @NonNull EffectiveStatement<?, ?>> parentPath = parentSchema.statementPath();
            if (parentPath.isEmpty() || !(parentPath.get(parentPath.size() - 1) instanceof OperationDefinition)) {
                iiToDataList.add(result.getIdentifier());
            }
        }
    } else {
        if (result instanceof MapNode) {
            result = Iterables.getOnlyElement(((MapNode) result).body());
        }
    }
    final YangInstanceIdentifier fullIIToData = YangInstanceIdentifier.create(Iterables.concat(path.getInstanceIdentifier().getPathArguments(), iiToDataList));
    newIIContext = new InstanceIdentifierContext<>(fullIIToData, path.getSchemaNode(), path.getMountPoint(), path.getSchemaContext());
    // FIXME: can result really be null?
    return NormalizedNodePayload.ofNullable(newIIContext, result);
}
Also used : SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) OperationDefinition(org.opendaylight.yangtools.yang.model.api.OperationDefinition) JSONCodecFactorySupplier(org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier) Iterables(com.google.common.collect.Iterables) Provider(javax.ws.rs.ext.Provider) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) EffectiveStatementInference(org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference) LoggerFactory(org.slf4j.LoggerFactory) DOMMountPointService(org.opendaylight.mdsal.dom.api.DOMMountPointService) NormalizedNodePayload(org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) ErrorType(org.opendaylight.yangtools.yang.common.ErrorType) Absolute(org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute) MediaType(javax.ws.rs.core.MediaType) ResultAlreadySetException(org.opendaylight.yangtools.yang.data.impl.schema.ResultAlreadySetException) Consumes(javax.ws.rs.Consumes) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) SchemaContextHandler(org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler) MapNode(org.opendaylight.yangtools.yang.data.api.schema.MapNode) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) EffectiveStatement(org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement) DataContainerNode(org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode) Logger(org.slf4j.Logger) SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) ErrorTag(org.opendaylight.yangtools.yang.common.ErrorTag) Throwables(com.google.common.base.Throwables) RpcEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) MediaTypes(org.opendaylight.restconf.nb.rfc8040.MediaTypes) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) List(java.util.List) AugmentationNode(org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) JsonParserStream(org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream) WebApplicationException(javax.ws.rs.WebApplicationException) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) NonNull(org.eclipse.jdt.annotation.NonNull) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) InputStream(java.io.InputStream) ChoiceNode(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) JsonParserStream(org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream) RpcEffectiveStatement(org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement) EffectiveStatementInference(org.opendaylight.yangtools.yang.model.api.EffectiveStatementInference) ArrayList(java.util.ArrayList) DataContainerNode(org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode) MapNode(org.opendaylight.yangtools.yang.data.api.schema.MapNode) NonNull(org.eclipse.jdt.annotation.NonNull) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) JsonReader(com.google.gson.stream.JsonReader) ChoiceNode(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) OperationDefinition(org.opendaylight.yangtools.yang.model.api.OperationDefinition) InputStreamReader(java.io.InputStreamReader) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) MapEntryNode(org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) AugmentationNode(org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode)

Example 5 with EffectiveStatement

use of org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement in project netconf by opendaylight.

the class XmlPatchBodyReader method parse.

private static PatchContext parse(final InstanceIdentifierContext<?> pathContext, final Document doc) throws XMLStreamException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
    final List<PatchEntity> resultCollection = new ArrayList<>();
    final String patchId = doc.getElementsByTagName("patch-id").item(0).getFirstChild().getNodeValue();
    final NodeList editNodes = doc.getElementsByTagName("edit");
    for (int i = 0; i < editNodes.getLength(); i++) {
        DataSchemaNode schemaNode = (DataSchemaNode) pathContext.getSchemaNode();
        final Element element = (Element) editNodes.item(i);
        final String operation = element.getElementsByTagName("operation").item(0).getFirstChild().getNodeValue();
        final PatchEditOperation oper = PatchEditOperation.valueOf(operation.toUpperCase(Locale.ROOT));
        final String editId = element.getElementsByTagName("edit-id").item(0).getFirstChild().getNodeValue();
        final String target = element.getElementsByTagName("target").item(0).getFirstChild().getNodeValue();
        final List<Element> values = readValueNodes(element, oper);
        final Element firstValueElement = values != null ? values.get(0) : null;
        // find complete path to target and target schema node
        // target can be also empty (only slash)
        YangInstanceIdentifier targetII;
        final SchemaNode targetNode;
        final Inference inference;
        if (target.equals("/")) {
            targetII = pathContext.getInstanceIdentifier();
            targetNode = pathContext.getSchemaContext();
            inference = Inference.ofDataTreePath(pathContext.getSchemaContext(), schemaNode.getQName());
        } else {
            // interpret as simple context
            targetII = ParserIdentifier.parserPatchTarget(pathContext, target);
            // move schema node
            schemaNode = verifyNotNull(DataSchemaContextTree.from(pathContext.getSchemaContext()).findChild(targetII).orElseThrow().getDataSchemaNode());
            final SchemaInferenceStack stack = SchemaInferenceStack.of(pathContext.getSchemaContext());
            targetII.getPathArguments().stream().filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates)).filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier)).forEach(p -> stack.enterSchemaTree(p.getNodeType()));
            final EffectiveStatement<?, ?> parentStmt = stack.exit();
            verify(parentStmt instanceof SchemaNode, "Unexpected parent %s", parentStmt);
            targetNode = (SchemaNode) parentStmt;
            inference = stack.toInference();
        }
        if (targetNode == null) {
            LOG.debug("Target node {} not found in path {} ", target, pathContext.getSchemaNode());
            throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
        }
        if (oper.isWithValue()) {
            final NormalizedNode parsed;
            if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
                final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
                final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
                final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
                xmlParser.traverse(new DOMSource(firstValueElement));
                parsed = resultHolder.getResult();
            } else {
                parsed = null;
            }
            // for lists allow to manipulate with list items through their parent
            if (targetII.getLastPathArgument() instanceof NodeIdentifierWithPredicates) {
                targetII = targetII.getParent();
            }
            resultCollection.add(new PatchEntity(editId, oper, targetII, parsed));
        } else {
            resultCollection.add(new PatchEntity(editId, oper, targetII));
        }
    }
    return new PatchContext(pathContext, ImmutableList.copyOf(resultCollection), patchId);
}
Also used : SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) Provider(javax.ws.rs.ext.Provider) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) UntrustedXML(org.opendaylight.yangtools.util.xml.UntrustedXML) Consumes(javax.ws.rs.Consumes) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) Locale(java.util.Locale) Document(org.w3c.dom.Document) XMLStreamException(javax.xml.stream.XMLStreamException) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) Inference(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference) MediaTypes(org.opendaylight.restconf.nb.rfc8040.MediaTypes) ParserIdentifier(org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserIdentifier) List(java.util.List) SAXException(org.xml.sax.SAXException) WebApplicationException(javax.ws.rs.WebApplicationException) NonNull(org.eclipse.jdt.annotation.NonNull) Verify.verifyNotNull(com.google.common.base.Verify.verifyNotNull) DOMSource(javax.xml.transform.dom.DOMSource) InstanceIdentifierContext(org.opendaylight.restconf.common.context.InstanceIdentifierContext) DOMMountPointService(org.opendaylight.mdsal.dom.api.DOMMountPointService) PatchEntity(org.opendaylight.restconf.common.patch.PatchEntity) ArrayList(java.util.ArrayList) ErrorType(org.opendaylight.yangtools.yang.common.ErrorType) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) SchemaContextHandler(org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler) XmlParserStream(org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream) Node(org.w3c.dom.Node) EffectiveStatement(org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) SchemaInferenceStack(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack) ErrorTag(org.opendaylight.yangtools.yang.common.ErrorTag) IOException(java.io.IOException) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) DataSchemaContextTree(org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) Element(org.w3c.dom.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) InputStream(java.io.InputStream) PatchEditOperation(org.opendaylight.restconf.common.patch.PatchEditOperation) XmlParserStream(org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream) RestconfDocumentedException(org.opendaylight.restconf.common.errors.RestconfDocumentedException) DOMSource(javax.xml.transform.dom.DOMSource) PatchEntity(org.opendaylight.restconf.common.patch.PatchEntity) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) NormalizedNodeResult(org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) PatchEditOperation(org.opendaylight.restconf.common.patch.PatchEditOperation) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) NodeList(org.w3c.dom.NodeList) Inference(org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference) ImmutableNormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter) NormalizedNodeStreamWriter(org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) ContainerSchemaNode(org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode) SchemaNode(org.opendaylight.yangtools.yang.model.api.SchemaNode) DataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode) PatchContext(org.opendaylight.restconf.common.patch.PatchContext) ListSchemaNode(org.opendaylight.yangtools.yang.model.api.ListSchemaNode) NodeIdentifierWithPredicates(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates)

Aggregations

EffectiveStatement (org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement)7 NonNull (org.eclipse.jdt.annotation.NonNull)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 SchemaNode (org.opendaylight.yangtools.yang.model.api.SchemaNode)4 Verify.verify (com.google.common.base.Verify.verify)3 Verify.verifyNotNull (com.google.common.base.Verify.verifyNotNull)3 InputStream (java.io.InputStream)3 Consumes (javax.ws.rs.Consumes)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 Provider (javax.ws.rs.ext.Provider)3 InstanceIdentifierContext (org.opendaylight.restconf.common.context.InstanceIdentifierContext)3 RestconfDocumentedException (org.opendaylight.restconf.common.errors.RestconfDocumentedException)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 ImmutableList (com.google.common.collect.ImmutableList)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 DOMMountPointService (org.opendaylight.mdsal.dom.api.DOMMountPointService)2 MediaTypes (org.opendaylight.restconf.nb.rfc8040.MediaTypes)2