Use instanceof patterns in netconf-util
[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 xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
150         try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
151              var writer = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
152             writer.write(normalized);
153             writer.flush();
154         } finally {
155             xmlWriter.close();
156         }
157     }
158
159     /**
160      * Write {@code normalized} data along with corresponding {@code metadata} into {@link DOMResult}.
161      *
162      * @param normalized data to be written
163      * @param metadata   metadata to be written
164      * @param result     DOM result holder
165      * @param schemaPath schema path of the parent node
166      * @param context    mountpoint schema context
167      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
168      * @throws XMLStreamException when failed to serialize data into XML document
169      */
170     public static void writeNormalizedNode(final NormalizedNode normalized, final @Nullable NormalizedMetadata metadata,
171             final DOMResult result, final SchemaPath schemaPath, final EffectiveModelContext context)
172                 throws IOException, XMLStreamException {
173         if (metadata == null) {
174             writeNormalizedNode(normalized, result, schemaPath, context);
175             return;
176         }
177
178         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
179         XML_NAMESPACE_SETTER.initializeNamespace(xmlWriter);
180         try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
181              var writer = NormalizedMetadataWriter.forStreamWriter(streamWriter)) {
182             writer.write(normalized, metadata);
183             writer.flush();
184         } finally {
185             xmlWriter.close();
186         }
187     }
188
189     /**
190      * Write data specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
191      *
192      * @param query      path to the root node
193      * @param result     DOM result holder
194      * @param schemaPath schema path of the parent node
195      * @param context    mountpoint schema context
196      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
197      * @throws XMLStreamException when failed to serialize data into XML document
198      */
199     public static void writeNormalizedNode(final YangInstanceIdentifier query, final DOMResult result,
200             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
201         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
202         XML_NAMESPACE_SETTER.initializeNamespace(xmlWriter);
203         try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
204              var writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
205             final Iterator<PathArgument> it = query.getPathArguments().iterator();
206             final PathArgument first = it.next();
207             StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first, it);
208         } finally {
209             xmlWriter.close();
210         }
211     }
212
213     /**
214      * Write data specified by {@link YangInstanceIdentifier} along with corresponding {@code metadata}
215      * into {@link DOMResult}.
216      *
217      * @param query      path to the root node
218      * @param metadata   metadata to be written
219      * @param result     DOM result holder
220      * @param schemaPath schema path of the parent node
221      * @param context    mountpoint schema context
222      * @throws IOException        when failed to write data into {@link NormalizedNodeStreamWriter}
223      * @throws XMLStreamException when failed to serialize data into XML document
224      */
225     public static void writeNormalizedNode(final YangInstanceIdentifier query,
226             final @Nullable NormalizedMetadata metadata, final DOMResult result, final SchemaPath schemaPath,
227             final EffectiveModelContext context) throws IOException, XMLStreamException {
228         if (metadata == null) {
229             writeNormalizedNode(query, result, schemaPath, context);
230             return;
231         }
232
233         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
234         XML_NAMESPACE_SETTER.initializeNamespace(xmlWriter);
235         try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
236              var writer = new EmptyListXmlMetadataWriter(streamWriter, xmlWriter,
237                  streamWriter.getExtensions().getInstance(StreamWriterMetadataExtension.class), metadata)) {
238             final Iterator<PathArgument> it = query.getPathArguments().iterator();
239             final PathArgument first = it.next();
240             StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first, it);
241         } finally {
242             xmlWriter.close();
243         }
244     }
245
246     /**
247      * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
248      *
249      * @param query      path to the root node
250      * @param result     DOM result holder
251      * @param schemaPath schema path of the parent node
252      * @param context    mountpoint schema context
253      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
254      * @throws XMLStreamException failed to serialize filter into XML document
255      */
256     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
257             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
258         if (query.isEmpty()) {
259             // No query at all
260             return;
261         }
262
263         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
264         try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
265              var writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
266             final Iterator<PathArgument> it = query.getPathArguments().iterator();
267             final PathArgument first = it.next();
268             StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first, it);
269         } finally {
270             xmlWriter.close();
271         }
272     }
273
274     /**
275      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
276      * into {@link DOMResult}. Field paths are relative to parent query path.
277      *
278      * @param query      path to the root node
279      * @param result     DOM result holder
280      * @param schemaPath schema path of the parent node
281      * @param context    mountpoint schema context
282      * @param fields     list of specific fields for which the filter should be created
283      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
284      * @throws XMLStreamException failed to serialize filter into XML document
285      * @throws NullPointerException if any argument is null
286      */
287     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
288                                    final SchemaPath schemaPath, final EffectiveModelContext context,
289                                    final List<YangInstanceIdentifier> fields) throws IOException, XMLStreamException {
290         if (query.isEmpty() || fields.isEmpty()) {
291             // No query at all
292             return;
293         }
294
295         final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
296         final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
297
298         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
299         try {
300             try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
301                  var writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
302                 final PathArgument first = rootNode.element();
303                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType())
304                         .streamToWriter(writer, first, rootNode);
305             }
306         } finally {
307             xmlWriter.close();
308         }
309     }
310
311     /**
312      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
313      * into {@link Element}. Field paths are relative to parent query path. Filter is created without following
314      * {@link EffectiveModelContext}.
315      *
316      * @param query         path to the root node
317      * @param fields        list of specific fields for which the filter should be created
318      * @param filterElement XML filter element to which the created filter will be written
319      */
320     public static void writeSchemalessFilter(final YangInstanceIdentifier query,
321                                              final List<YangInstanceIdentifier> fields, final Element filterElement) {
322         pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
323     }
324
325     private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
326         final PathArgument pathArg = pathArgumentTree.element();
327
328         final QName nodeType = pathArg.getNodeType();
329         final String elementNamespace = nodeType.getNamespace().toString();
330
331         if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
332             // element has already been written as list key
333             return;
334         }
335
336         final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
337         data.appendChild(childElement);
338         if (pathArg instanceof NodeIdentifierWithPredicates nip) {
339             appendListKeyNodes(childElement, nip);
340         }
341         for (final PathNode childrenNode : pathArgumentTree.children()) {
342             pathArgumentTreeToXmlStructure(childrenNode, childElement);
343         }
344     }
345
346     /**
347      * Appending list key elements to parent element.
348      *
349      * @param parentElement parent XML element to which children elements are appended
350      * @param listEntryId   list entry identifier
351      */
352     public static void appendListKeyNodes(final Element parentElement, final NodeIdentifierWithPredicates listEntryId) {
353         for (Entry<QName, Object> key : listEntryId.entrySet()) {
354             final Element keyElement = parentElement.getOwnerDocument().createElementNS(
355                     key.getKey().getNamespace().toString(), key.getKey().getLocalName());
356             keyElement.setTextContent(key.getValue().toString());
357             parentElement.appendChild(keyElement);
358         }
359     }
360
361     /**
362      * Aggregation of the fields paths based on parenthesis. Only parent/enclosing {@link YangInstanceIdentifier}
363      * are kept. For example, paths '/x/y/z', '/x/y', and '/x' are aggregated into single field path: '/x'
364      *
365      * @param fields paths of fields
366      * @return filtered {@link List} of paths
367      */
368     private static List<YangInstanceIdentifier> aggregateFields(final List<YangInstanceIdentifier> fields) {
369         return fields.stream()
370                 .filter(field -> fields.stream()
371                         .filter(fieldYiid -> !field.equals(fieldYiid))
372                         .noneMatch(fieldYiid -> fieldYiid.contains(field)))
373                 .collect(Collectors.toList());
374     }
375
376     /**
377      * Construct a tree based on the parent {@link YangInstanceIdentifier} and provided list of fields. The goal of this
378      * procedure is the elimination of the redundancy that is introduced by potentially overlapping parts of the fields
379      * paths.
380      *
381      * @param query  path to parent element
382      * @param fields subpaths relative to parent path that identify specific fields
383      * @return created {@link PathNode} structure
384      */
385     private static PathNode constructPathArgumentTree(final YangInstanceIdentifier query,
386             final List<YangInstanceIdentifier> fields) {
387         final Iterator<PathArgument> queryIterator = query.getPathArguments().iterator();
388         final PathNode rootTreeNode = new PathNode(queryIterator.next());
389
390         PathNode queryTreeNode = rootTreeNode;
391         while (queryIterator.hasNext()) {
392             queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
393         }
394
395         for (final YangInstanceIdentifier field : fields) {
396             PathNode actualFieldTreeNode = queryTreeNode;
397             for (final PathArgument fieldPathArg : field.getPathArguments()) {
398                 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
399             }
400         }
401         return rootTreeNode;
402     }
403
404     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final MountPointContext mount,
405             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
406         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
407         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
408         try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, new ProxyMountPointContext(mount))) {
409             xmlParserStream.traverse(value);
410         }
411         return resultHolder;
412     }
413
414     // FIXME: document this interface contract. Does it support RFC8528/RFC8542? How?
415     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final EffectiveModelContext schemaContext,
416             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
417         return transformDOMSourceToNormalizedNode(new EmptyMountPointContext(schemaContext), value);
418     }
419 }