Fix AbstractGet.transformNormalizedNode()
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / AbstractEdit.java
1 /*
2  * Copyright (c) 2018 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.mdsal.connector.ops;
9
10 import com.google.common.collect.ImmutableMap;
11 import java.io.IOException;
12 import java.net.URISyntaxException;
13 import java.util.Iterator;
14 import javax.xml.stream.XMLStreamException;
15 import javax.xml.transform.dom.DOMSource;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.netconf.api.DocumentedException;
18 import org.opendaylight.netconf.api.NetconfDocumentedException;
19 import org.opendaylight.netconf.api.xml.XmlElement;
20 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
21 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
22 import org.opendaylight.yangtools.yang.common.ErrorTag;
23 import org.opendaylight.yangtools.yang.common.ErrorType;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.XMLNamespace;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
30 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaTreeInference;
33 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Element;
37 import org.w3c.dom.NodeList;
38 import org.xml.sax.SAXException;
39
40 abstract class AbstractEdit extends AbstractConfigOperation {
41     private static final Logger LOG = LoggerFactory.getLogger(AbstractEdit.class);
42     private static final String TARGET_KEY = "target";
43
44     final CurrentSchemaContext schemaContext;
45
46     AbstractEdit(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext) {
47         super(netconfSessionIdForReporting);
48         this.schemaContext = schemaContext;
49     }
50
51     static final void parseIntoNormalizedNode(final SchemaTreeInference inference, final XmlElement element,
52                                               final NormalizedNodeStreamWriter writer) throws DocumentedException {
53         final var path = inference.statementPath();
54         final var schemaNode = path.get(path.size() - 1);
55         if (!(schemaNode instanceof ContainerSchemaNode) && !(schemaNode instanceof ListSchemaNode)) {
56             // This should never happen since any edit operation on any other node type
57             // should not be possible nor makes sense
58             LOG.debug("DataNode from module is not ContainerSchemaNode nor ListSchemaNode, aborting..");
59             throw new UnsupportedOperationException("implement exception if parse fails");
60         }
61
62         final XmlParserStream xmlParser = XmlParserStream.create(writer, inference);
63         try {
64             xmlParser.traverse(new DOMSource(element.getDomElement()));
65         } catch (final XMLStreamException | URISyntaxException | IOException | SAXException ex) {
66             throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex,
67                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
68         }
69     }
70
71     final SchemaTreeInference getSchemaNodeFromNamespace(final String namespace, final XmlElement element)
72             throws DocumentedException {
73         final XMLNamespace ns;
74         try {
75             ns = XMLNamespace.of(namespace);
76         } catch (final IllegalArgumentException e) {
77             throw new NetconfDocumentedException("Unable to create URI for namespace : " + namespace, e,
78                 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, ErrorSeverity.ERROR);
79         }
80
81         // Returns module with newest revision since findModuleByNamespace returns a set of modules and we only
82         // need the newest one
83         final EffectiveModelContext ctx = schemaContext.getCurrentContext();
84         final Iterator<? extends @NonNull Module> it = ctx.findModules(ns).iterator();
85         if (!it.hasNext()) {
86             // No module is present with this namespace
87             throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
88                 ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
89         }
90
91         final Module module = it.next();
92         final SchemaInferenceStack stack = SchemaInferenceStack.of(ctx);
93         final String elementName = element.getName();
94         try {
95             // FIXME: This is a bit suspect. The element is formed using XML encoding, hence it corresponds to
96             //        enterDataTree(). But then we use the result of this method to create a NormalizedNode tree,
97             //        which contains ChoiceNode. This needs to be tested with something like to following:
98             //
99             //        module mod {
100             //          choice foo {
101             //            case bar {
102             //              leaf baz {
103             //                type string;
104             //              }
105             //            }
106             //          }
107             //        }
108             stack.enterSchemaTree(QName.create(module.getQNameModule(), elementName));
109         } catch (IllegalArgumentException e) {
110             throw new DocumentedException(
111                 "Unable to find node " + elementName + " with namespace: " + namespace + " in module: " + module, e,
112                 ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
113         }
114
115         return stack.toSchemaTreeInference();
116     }
117
118     static final XmlElement extractTargetElement(final XmlElement operationElement, final String operationName)
119         throws DocumentedException {
120         final NodeList elementsByTagName = getElementsByTagName(operationElement, TARGET_KEY);
121         // Direct lookup instead of using XmlElement class due to performance
122         if (elementsByTagName.getLength() == 0) {
123             throw new DocumentedException("Missing target element", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE,
124                 ErrorSeverity.ERROR, ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element", operationName));
125         } else if (elementsByTagName.getLength() > 1) {
126             throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE,
127                 ErrorSeverity.ERROR);
128         } else {
129             return XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
130         }
131     }
132 }