Bump MRI upstreams
[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 com.google.common.collect.ImmutableMap;
13 import java.io.IOException;
14 import java.net.URISyntaxException;
15 import java.util.Iterator;
16 import java.util.List;
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.util.NormalizedMetadataWriter;
31 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
32 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.Revision;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
42 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Document;
52 import org.w3c.dom.Element;
53 import org.xml.sax.SAXException;
54
55 public final class NetconfUtil {
56     /**
57      * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
58      * Specifically:
59      * <ul>
60      *   <li>OpenJDK DOM writer (com.sun.xml.internal.stream.writers.XMLDOMWriterImpl) throws
61      *       UnsupportedOperationException from its setNamespaceContext() method</li>
62      *   <li>Woodstox DOM writer (com.ctc.wstx.dom.WstxDOMWrappingWriter) works with namespace context, but treats
63      *       setPrefix() calls as hints -- which are not discoverable.</li>
64      * </ul>
65      *
66      * <p>
67      * Due to this we perform a quick test for behavior and decide the appropriate strategy.
68      */
69     @FunctionalInterface
70     private interface NamespaceSetter {
71         void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
72
73         static NamespaceSetter forFactory(final XMLOutputFactory xmlFactory) {
74             final String netconfNamespace = NETCONF_QNAME.getNamespace().toString();
75             final AnyXmlNamespaceContext namespaceContext = new AnyXmlNamespaceContext(ImmutableMap.of(
76                 "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.warn("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     @SuppressWarnings("checkstyle:IllegalCatch")
138     public static void writeNormalizedNode(final NormalizedNode normalized, final DOMResult result,
139                                            final SchemaPath schemaPath, final EffectiveModelContext context)
140             throws IOException, XMLStreamException {
141         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
142         try (
143              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
144                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
145              NormalizedNodeWriter normalizedNodeWriter =
146                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
147         ) {
148             normalizedNodeWriter.write(normalized);
149             normalizedNodeWriter.flush();
150         } finally {
151             try {
152                 if (writer != null) {
153                     writer.close();
154                 }
155             } catch (final Exception e) {
156                 LOG.warn("Unable to close resource properly", e);
157             }
158         }
159     }
160
161     @SuppressWarnings("checkstyle:IllegalCatch")
162     public static void writeNormalizedNode(final NormalizedNode normalized,
163                                            final @Nullable NormalizedMetadata metadata,
164                                            final DOMResult result, final SchemaPath schemaPath,
165                                            final EffectiveModelContext context) throws IOException, XMLStreamException {
166         if (metadata == null) {
167             writeNormalizedNode(normalized, result, schemaPath, context);
168             return;
169         }
170
171         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
172         XML_NAMESPACE_SETTER.initializeNamespace(writer);
173         try (
174              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
175                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
176                 NormalizedMetadataWriter normalizedNodeWriter =
177                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
178         ) {
179             normalizedNodeWriter.write(normalized, metadata);
180             normalizedNodeWriter.flush();
181         } finally {
182             try {
183                 if (writer != null) {
184                     writer.close();
185                 }
186             } catch (final Exception e) {
187                 LOG.warn("Unable to close resource properly", e);
188             }
189         }
190     }
191
192     /**
193      * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
194      *
195      * @param query      path to the root node
196      * @param result     DOM result holder
197      * @param schemaPath schema path of the parent node
198      * @param context    mountpoint schema context
199      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
200      * @throws XMLStreamException failed to serialize filter into XML document
201      */
202     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
203             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
204         if (query.isEmpty()) {
205             // No query at all
206             return;
207         }
208
209         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
210         try {
211             try (NormalizedNodeStreamWriter streamWriter =
212                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, 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,
217                     it);
218             }
219         } finally {
220             xmlWriter.close();
221         }
222     }
223
224     /**
225      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
226      * into {@link DOMResult}. Field paths are relative to parent query path.
227      *
228      * @param query      path to the root node
229      * @param result     DOM result holder
230      * @param schemaPath schema path of the parent node
231      * @param context    mountpoint schema context
232      * @param fields     list of specific fields for which the filter should be created
233      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
234      * @throws XMLStreamException failed to serialize filter into XML document
235      * @throws NullPointerException if any argument is null
236      */
237     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
238                                    final SchemaPath schemaPath, final EffectiveModelContext context,
239                                    final List<YangInstanceIdentifier> fields) throws IOException, XMLStreamException {
240         if (query.isEmpty() || fields.isEmpty()) {
241             // No query at all
242             return;
243         }
244         final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
245         final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
246
247         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
248         try {
249             try (NormalizedNodeStreamWriter streamWriter =
250                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
251                  EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
252                 final PathArgument first = rootNode.element();
253                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType())
254                         .streamToWriter(writer, first, rootNode);
255             }
256         } finally {
257             xmlWriter.close();
258         }
259     }
260
261     /**
262      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
263      * into {@link Element}. Field paths are relative to parent query path. Filter is created without following
264      * {@link EffectiveModelContext}.
265      *
266      * @param query         path to the root node
267      * @param fields        list of specific fields for which the filter should be created
268      * @param filterElement XML filter element to which the created filter will be written
269      */
270     public static void writeSchemalessFilter(final YangInstanceIdentifier query,
271                                              final List<YangInstanceIdentifier> fields, final Element filterElement) {
272         pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
273     }
274
275     private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
276         final PathArgument pathArg = pathArgumentTree.element();
277
278         final QName nodeType = pathArg.getNodeType();
279         final String elementNamespace = nodeType.getNamespace().toString();
280
281         if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
282             // element has already been written as list key
283             return;
284         }
285
286         final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
287         data.appendChild(childElement);
288         if (pathArg instanceof NodeIdentifierWithPredicates) {
289             appendListKeyNodes(childElement, (NodeIdentifierWithPredicates) pathArg);
290         }
291         for (final PathNode childrenNode : pathArgumentTree.children()) {
292             pathArgumentTreeToXmlStructure(childrenNode, childElement);
293         }
294     }
295
296     /**
297      * Appending list key elements to parent element.
298      *
299      * @param parentElement parent XML element to which children elements are appended
300      * @param listEntryId   list entry identifier
301      */
302     public static void appendListKeyNodes(final Element parentElement, final NodeIdentifierWithPredicates listEntryId) {
303         for (Entry<QName, Object> key : listEntryId.entrySet()) {
304             final Element keyElement = parentElement.getOwnerDocument().createElementNS(
305                     key.getKey().getNamespace().toString(), key.getKey().getLocalName());
306             keyElement.setTextContent(key.getValue().toString());
307             parentElement.appendChild(keyElement);
308         }
309     }
310
311     /**
312      * Aggregation of the fields paths based on parenthesis. Only parent/enclosing {@link YangInstanceIdentifier}
313      * are kept. For example, paths '/x/y/z', '/x/y', and '/x' are aggregated into single field path: '/x'
314      *
315      * @param fields paths of fields
316      * @return filtered {@link List} of paths
317      */
318     private static List<YangInstanceIdentifier> aggregateFields(final List<YangInstanceIdentifier> fields) {
319         return fields.stream()
320                 .filter(field -> fields.stream()
321                         .filter(fieldYiid -> !field.equals(fieldYiid))
322                         .noneMatch(fieldYiid -> fieldYiid.contains(field)))
323                 .collect(Collectors.toList());
324     }
325
326     /**
327      * Construct a tree based on the parent {@link YangInstanceIdentifier} and provided list of fields. The goal of this
328      * procedure is the elimination of the redundancy that is introduced by potentially overlapping parts of the fields
329      * paths.
330      *
331      * @param query  path to parent element
332      * @param fields subpaths relative to parent path that identify specific fields
333      * @return created {@link TreeNode} structure
334      */
335     private static PathNode constructPathArgumentTree(final YangInstanceIdentifier query,
336             final List<YangInstanceIdentifier> fields) {
337         final Iterator<PathArgument> queryIterator = query.getPathArguments().iterator();
338         final PathNode rootTreeNode = new PathNode(queryIterator.next());
339
340         PathNode queryTreeNode = rootTreeNode;
341         while (queryIterator.hasNext()) {
342             queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
343         }
344
345         for (final YangInstanceIdentifier field : fields) {
346             PathNode actualFieldTreeNode = queryTreeNode;
347             for (final PathArgument fieldPathArg : field.getPathArguments()) {
348                 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
349             }
350         }
351         return rootTreeNode;
352     }
353
354     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final MountPointContext mount,
355             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
356         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
357         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
358         try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, new ProxyMountPointContext(mount))) {
359             xmlParserStream.traverse(value);
360         }
361         return resultHolder;
362     }
363
364     // FIXME: document this interface contract. Does it support RFC8528/RFC8542? How?
365     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final EffectiveModelContext schemaContext,
366             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
367         return transformDOMSourceToNormalizedNode(new EmptyMountPointContext(schemaContext), value);
368     }
369 }