7a068735964ba3e9f9e7714220b2e8cdd671cc61
[netconf.git] / netconf / netconf-util / src / main / java / org / opendaylight / netconf / util / NetconfUtil.java
1 /*
2  * Copyright (c) 2013 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.util;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.io.IOException;
13 import java.net.URISyntaxException;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.stream.Collectors;
19 import javax.xml.stream.XMLOutputFactory;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.stream.XMLStreamWriter;
22 import javax.xml.transform.dom.DOMResult;
23 import javax.xml.transform.dom.DOMSource;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.netconf.api.DocumentedException;
26 import org.opendaylight.netconf.api.xml.XmlElement;
27 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
28 import org.opendaylight.netconf.api.xml.XmlUtil;
29 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
30 import org.opendaylight.yangtools.rfc7952.data.api.StreamWriterMetadataExtension;
31 import org.opendaylight.yangtools.rfc7952.data.util.NormalizedMetadataWriter;
32 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
33 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.common.QNameModule;
36 import org.opendaylight.yangtools.yang.common.Revision;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Element;
54 import org.xml.sax.SAXException;
55
56 public final class NetconfUtil {
57     /**
58      * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
59      * Specifically:
60      * <ul>
61      *   <li>OpenJDK DOM writer (com.sun.xml.internal.stream.writers.XMLDOMWriterImpl) throws
62      *       UnsupportedOperationException from its setNamespaceContext() method</li>
63      *   <li>Woodstox DOM writer (com.ctc.wstx.dom.WstxDOMWrappingWriter) works with namespace context, but treats
64      *       setPrefix() calls as hints -- which are not discoverable.</li>
65      * </ul>
66      *
67      * <p>
68      * Due to this we perform a quick test for behavior and decide the appropriate strategy.
69      */
70     @FunctionalInterface
71     private interface NamespaceSetter {
72         void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
73
74         static NamespaceSetter forFactory(final XMLOutputFactory xmlFactory) {
75             final String netconfNamespace = NETCONF_QNAME.getNamespace().toString();
76             final AnyXmlNamespaceContext namespaceContext = new AnyXmlNamespaceContext(Map.of("op", netconfNamespace));
77
78             try {
79                 final XMLStreamWriter testWriter = xmlFactory.createXMLStreamWriter(new DOMResult(
80                     XmlUtil.newDocument()));
81                 testWriter.setNamespaceContext(namespaceContext);
82             } catch (final UnsupportedOperationException e) {
83                 // This happens with JDK's DOM writer, which we may be using
84                 LOG.debug("Unable to set namespace context, falling back to setPrefix()", e);
85                 return writer -> writer.setPrefix("op", netconfNamespace);
86             } catch (XMLStreamException e) {
87                 throw new ExceptionInInitializerError(e);
88             }
89
90             // Success, we can use setNamespaceContext()
91             return writer -> writer.setNamespaceContext(namespaceContext);
92         }
93     }
94
95     private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
96
97     // FIXME: document what exactly this QName means, as it is not referring to a tangible node nor the ietf-module.
98     // FIXME: what is this contract saying?
99     //        - is it saying all data is going to be interpreted with this root?
100     //        - is this saying we are following a specific interface contract (i.e. do we have schema mounts?)
101     //        - is it also inferring some abilities w.r.t. RFC8342?
102     public static final QName NETCONF_QNAME = QName.create(QNameModule.create(SchemaContext.NAME.getNamespace(),
103         Revision.of("2011-06-01")), "netconf").intern();
104     // FIXME: is this the device-bound revision?
105     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
106
107     public static final XMLOutputFactory XML_FACTORY;
108
109     static {
110         final XMLOutputFactory f = XMLOutputFactory.newFactory();
111         // FIXME: not repairing namespaces is probably common, this should be availabe as common XML constant.
112         f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
113         XML_FACTORY = f;
114     }
115
116     private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
117
118     private NetconfUtil() {
119         // No-op
120     }
121
122     public static Document checkIsMessageOk(final Document response) throws DocumentedException {
123         final XmlElement docElement = XmlElement.fromDomDocument(response);
124         // FIXME: we should throw DocumentedException here
125         checkState(XmlNetconfConstants.RPC_REPLY_KEY.equals(docElement.getName()));
126         final XmlElement element = docElement.getOnlyChildElement();
127         if (XmlNetconfConstants.OK.equals(element.getName())) {
128             return response;
129         }
130
131         LOG.warn("Can not load last configuration. Operation failed.");
132         // FIXME: we should be throwing a DocumentedException here
133         throw new IllegalStateException("Can not load last configuration. Operation failed: "
134                 + XmlUtil.toString(response));
135     }
136
137     /**
138      * Write {@code normalized} data into {@link DOMResult}.
139      *
140      * @param normalized data to be written
141      * @param result     DOM result holder
142      * @param schemaPath schema path of the parent node
143      * @param context    mountpoint schema context
144      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
145      * @throws XMLStreamException when failed to serialize data into XML document
146      */
147     public static void writeNormalizedNode(final NormalizedNode normalized, final DOMResult result,
148             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
149         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
150         try (
151              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
152                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
153              NormalizedNodeWriter normalizedNodeWriter =
154                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
155         ) {
156             normalizedNodeWriter.write(normalized);
157             normalizedNodeWriter.flush();
158         } finally {
159             writer.close();
160         }
161     }
162
163     /**
164      * Write {@code normalized} data along with corresponding {@code metadata} into {@link DOMResult}.
165      *
166      * @param normalized data to be written
167      * @param metadata   metadata to be written
168      * @param result     DOM result holder
169      * @param schemaPath schema path of the parent node
170      * @param context    mountpoint schema context
171      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
172      * @throws XMLStreamException when failed to serialize data into XML document
173      */
174     public static void writeNormalizedNode(final NormalizedNode normalized, final @Nullable NormalizedMetadata metadata,
175             final DOMResult result, final SchemaPath schemaPath, final EffectiveModelContext context)
176                 throws IOException, XMLStreamException {
177         if (metadata == null) {
178             writeNormalizedNode(normalized, result, schemaPath, context);
179             return;
180         }
181
182         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
183         XML_NAMESPACE_SETTER.initializeNamespace(writer);
184         try (
185              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
186                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
187                 NormalizedMetadataWriter normalizedNodeWriter =
188                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
189         ) {
190             normalizedNodeWriter.write(normalized, metadata);
191             normalizedNodeWriter.flush();
192         } finally {
193             writer.close();
194         }
195     }
196
197     /**
198      * Write data specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
199      *
200      * @param query      path to the root node
201      * @param result     DOM result holder
202      * @param schemaPath schema path of the parent node
203      * @param context    mountpoint schema context
204      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
205      * @throws XMLStreamException when failed to serialize data into XML document
206      */
207     public static void writeNormalizedNode(final YangInstanceIdentifier query, final DOMResult result,
208             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
209         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
210         XML_NAMESPACE_SETTER.initializeNamespace(xmlWriter);
211         try (NormalizedNodeStreamWriter streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
212                 context, schemaPath);
213              EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
214             final Iterator<PathArgument> it = query.getPathArguments().iterator();
215             final PathArgument first = it.next();
216             StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first, it);
217         } finally {
218             xmlWriter.close();
219         }
220     }
221
222     /**
223      * Write data specified by {@link YangInstanceIdentifier} along with corresponding {@code metadata}
224      * into {@link DOMResult}.
225      *
226      * @param query      path to the root node
227      * @param metadata   metadata to be written
228      * @param result     DOM result holder
229      * @param schemaPath schema path of the parent node
230      * @param context    mountpoint schema context
231      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
232      * @throws XMLStreamException when failed to serialize data into XML document
233      */
234     public static void writeNormalizedNode(final YangInstanceIdentifier query,
235             final @Nullable NormalizedMetadata metadata, final DOMResult result, final SchemaPath schemaPath,
236             final EffectiveModelContext context) throws IOException, XMLStreamException {
237         if (metadata == null) {
238             writeNormalizedNode(query, result, schemaPath, context);
239             return;
240         }
241
242         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
243         XML_NAMESPACE_SETTER.initializeNamespace(xmlWriter);
244         try (NormalizedNodeStreamWriter streamWriter = XMLStreamNormalizedNodeStreamWriter
245                 .create(xmlWriter, context, schemaPath);
246              EmptyListXmlMetadataWriter writer = new EmptyListXmlMetadataWriter(streamWriter, xmlWriter, streamWriter
247                      .getExtensions().getInstance(StreamWriterMetadataExtension.class), metadata)) {
248             final Iterator<PathArgument> it = query.getPathArguments().iterator();
249             final PathArgument first = it.next();
250             StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first, it);
251         } finally {
252             xmlWriter.close();
253         }
254     }
255
256     /**
257      * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
258      *
259      * @param query      path to the root node
260      * @param result     DOM result holder
261      * @param schemaPath schema path of the parent node
262      * @param context    mountpoint schema context
263      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
264      * @throws XMLStreamException failed to serialize filter into XML document
265      */
266     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
267             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
268         if (query.isEmpty()) {
269             // No query at all
270             return;
271         }
272
273         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
274         try {
275             try (NormalizedNodeStreamWriter streamWriter =
276                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
277                  EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
278                 final Iterator<PathArgument> it = query.getPathArguments().iterator();
279                 final PathArgument first = it.next();
280                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first,
281                     it);
282             }
283         } finally {
284             xmlWriter.close();
285         }
286     }
287
288     /**
289      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
290      * into {@link DOMResult}. Field paths are relative to parent query path.
291      *
292      * @param query      path to the root node
293      * @param result     DOM result holder
294      * @param schemaPath schema path of the parent node
295      * @param context    mountpoint schema context
296      * @param fields     list of specific fields for which the filter should be created
297      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
298      * @throws XMLStreamException failed to serialize filter into XML document
299      * @throws NullPointerException if any argument is null
300      */
301     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
302                                    final SchemaPath schemaPath, final EffectiveModelContext context,
303                                    final List<YangInstanceIdentifier> fields) throws IOException, XMLStreamException {
304         if (query.isEmpty() || fields.isEmpty()) {
305             // No query at all
306             return;
307         }
308         final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
309         final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
310
311         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
312         try {
313             try (NormalizedNodeStreamWriter streamWriter =
314                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
315                  EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
316                 final PathArgument first = rootNode.element();
317                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType())
318                         .streamToWriter(writer, first, rootNode);
319             }
320         } finally {
321             xmlWriter.close();
322         }
323     }
324
325     /**
326      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
327      * into {@link Element}. Field paths are relative to parent query path. Filter is created without following
328      * {@link EffectiveModelContext}.
329      *
330      * @param query         path to the root node
331      * @param fields        list of specific fields for which the filter should be created
332      * @param filterElement XML filter element to which the created filter will be written
333      */
334     public static void writeSchemalessFilter(final YangInstanceIdentifier query,
335                                              final List<YangInstanceIdentifier> fields, final Element filterElement) {
336         pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
337     }
338
339     private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
340         final PathArgument pathArg = pathArgumentTree.element();
341
342         final QName nodeType = pathArg.getNodeType();
343         final String elementNamespace = nodeType.getNamespace().toString();
344
345         if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
346             // element has already been written as list key
347             return;
348         }
349
350         final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
351         data.appendChild(childElement);
352         if (pathArg instanceof NodeIdentifierWithPredicates) {
353             appendListKeyNodes(childElement, (NodeIdentifierWithPredicates) pathArg);
354         }
355         for (final PathNode childrenNode : pathArgumentTree.children()) {
356             pathArgumentTreeToXmlStructure(childrenNode, childElement);
357         }
358     }
359
360     /**
361      * Appending list key elements to parent element.
362      *
363      * @param parentElement parent XML element to which children elements are appended
364      * @param listEntryId   list entry identifier
365      */
366     public static void appendListKeyNodes(final Element parentElement, final NodeIdentifierWithPredicates listEntryId) {
367         for (Entry<QName, Object> key : listEntryId.entrySet()) {
368             final Element keyElement = parentElement.getOwnerDocument().createElementNS(
369                     key.getKey().getNamespace().toString(), key.getKey().getLocalName());
370             keyElement.setTextContent(key.getValue().toString());
371             parentElement.appendChild(keyElement);
372         }
373     }
374
375     /**
376      * Aggregation of the fields paths based on parenthesis. Only parent/enclosing {@link YangInstanceIdentifier}
377      * are kept. For example, paths '/x/y/z', '/x/y', and '/x' are aggregated into single field path: '/x'
378      *
379      * @param fields paths of fields
380      * @return filtered {@link List} of paths
381      */
382     private static List<YangInstanceIdentifier> aggregateFields(final List<YangInstanceIdentifier> fields) {
383         return fields.stream()
384                 .filter(field -> fields.stream()
385                         .filter(fieldYiid -> !field.equals(fieldYiid))
386                         .noneMatch(fieldYiid -> fieldYiid.contains(field)))
387                 .collect(Collectors.toList());
388     }
389
390     /**
391      * Construct a tree based on the parent {@link YangInstanceIdentifier} and provided list of fields. The goal of this
392      * procedure is the elimination of the redundancy that is introduced by potentially overlapping parts of the fields
393      * paths.
394      *
395      * @param query  path to parent element
396      * @param fields subpaths relative to parent path that identify specific fields
397      * @return created {@link PathNode} structure
398      */
399     private static PathNode constructPathArgumentTree(final YangInstanceIdentifier query,
400             final List<YangInstanceIdentifier> fields) {
401         final Iterator<PathArgument> queryIterator = query.getPathArguments().iterator();
402         final PathNode rootTreeNode = new PathNode(queryIterator.next());
403
404         PathNode queryTreeNode = rootTreeNode;
405         while (queryIterator.hasNext()) {
406             queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
407         }
408
409         for (final YangInstanceIdentifier field : fields) {
410             PathNode actualFieldTreeNode = queryTreeNode;
411             for (final PathArgument fieldPathArg : field.getPathArguments()) {
412                 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
413             }
414         }
415         return rootTreeNode;
416     }
417
418     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final MountPointContext mount,
419             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
420         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
421         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
422         try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, new ProxyMountPointContext(mount))) {
423             xmlParserStream.traverse(value);
424         }
425         return resultHolder;
426     }
427
428     // FIXME: document this interface contract. Does it support RFC8528/RFC8542? How?
429     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final EffectiveModelContext schemaContext,
430             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
431         return transformDOMSourceToNormalizedNode(new EmptyMountPointContext(schemaContext), value);
432     }
433 }