Implement NodeContainerProxy.getPath()
[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.rcf8528.data.util.EmptyMountPointContext;
30 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
31 import org.opendaylight.yangtools.rfc7952.data.util.NormalizedMetadataWriter;
32 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
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.XmlCodecFactory;
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(ImmutableMap.of(
77                 "op", netconfNamespace));
78
79             try {
80                 final XMLStreamWriter testWriter = xmlFactory.createXMLStreamWriter(new DOMResult(
81                     XmlUtil.newDocument()));
82                 testWriter.setNamespaceContext(namespaceContext);
83             } catch (final UnsupportedOperationException e) {
84                 // This happens with JDK's DOM writer, which we may be using
85                 LOG.warn("Unable to set namespace context, falling back to setPrefix()", e);
86                 return writer -> writer.setPrefix("op", netconfNamespace);
87             } catch (XMLStreamException e) {
88                 throw new ExceptionInInitializerError(e);
89             }
90
91             // Success, we can use setNamespaceContext()
92             return writer -> writer.setNamespaceContext(namespaceContext);
93         }
94     }
95
96     private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
97
98     // FIXME: document what exactly this QName means, as it is not referring to a tangible node nor the ietf-module.
99     // FIXME: what is this contract saying?
100     //        - is it saying all data is going to be interpreted with this root?
101     //        - is this saying we are following a specific interface contract (i.e. do we have schema mounts?)
102     //        - is it also inferring some abilities w.r.t. RFC8342?
103     public static final QName NETCONF_QNAME = QName.create(QNameModule.create(SchemaContext.NAME.getNamespace(),
104         Revision.of("2011-06-01")), "netconf").intern();
105     // FIXME: is this the device-bound revision?
106     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
107
108     public static final XMLOutputFactory XML_FACTORY;
109
110     static {
111         final XMLOutputFactory f = XMLOutputFactory.newFactory();
112         // FIXME: not repairing namespaces is probably common, this should be availabe as common XML constant.
113         f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
114         XML_FACTORY = f;
115     }
116
117     private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
118
119     private NetconfUtil() {
120         // No-op
121     }
122
123     public static Document checkIsMessageOk(final Document response) throws DocumentedException {
124         final XmlElement docElement = XmlElement.fromDomDocument(response);
125         // FIXME: we should throw DocumentedException here
126         checkState(XmlNetconfConstants.RPC_REPLY_KEY.equals(docElement.getName()));
127         final XmlElement element = docElement.getOnlyChildElement();
128         if (XmlNetconfConstants.OK.equals(element.getName())) {
129             return response;
130         }
131
132         LOG.warn("Can not load last configuration. Operation failed.");
133         // FIXME: we should be throwing a DocumentedException here
134         throw new IllegalStateException("Can not load last configuration. Operation failed: "
135                 + XmlUtil.toString(response));
136     }
137
138     @SuppressWarnings("checkstyle:IllegalCatch")
139     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
140                                            final SchemaPath schemaPath, final EffectiveModelContext context)
141             throws IOException, XMLStreamException {
142         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
143         try (
144              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
145                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
146              NormalizedNodeWriter normalizedNodeWriter =
147                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
148         ) {
149             normalizedNodeWriter.write(normalized);
150             normalizedNodeWriter.flush();
151         } finally {
152             try {
153                 if (writer != null) {
154                     writer.close();
155                 }
156             } catch (final Exception e) {
157                 LOG.warn("Unable to close resource properly", e);
158             }
159         }
160     }
161
162     @SuppressWarnings("checkstyle:IllegalCatch")
163     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized,
164                                            final @Nullable NormalizedMetadata metadata,
165                                            final DOMResult result, final SchemaPath schemaPath,
166                                            final EffectiveModelContext context) throws IOException, XMLStreamException {
167         if (metadata == null) {
168             writeNormalizedNode(normalized, result, schemaPath, context);
169             return;
170         }
171
172         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
173         XML_NAMESPACE_SETTER.initializeNamespace(writer);
174         try (
175              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
176                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
177                 NormalizedMetadataWriter normalizedNodeWriter =
178                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
179         ) {
180             normalizedNodeWriter.write(normalized, metadata);
181             normalizedNodeWriter.flush();
182         } finally {
183             try {
184                 if (writer != null) {
185                     writer.close();
186                 }
187             } catch (final Exception e) {
188                 LOG.warn("Unable to close resource properly", e);
189             }
190         }
191     }
192
193     /**
194      * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
195      *
196      * @param query      path to the root node
197      * @param result     DOM result holder
198      * @param schemaPath schema path of the parent node
199      * @param context    mountpoint schema context
200      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
201      * @throws XMLStreamException failed to serialize filter into XML document
202      */
203     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
204             final SchemaPath schemaPath, final EffectiveModelContext context) throws IOException, XMLStreamException {
205         if (query.isEmpty()) {
206             // No query at all
207             return;
208         }
209
210         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
211         try {
212             try (NormalizedNodeStreamWriter streamWriter =
213                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
214                  EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
215                 final Iterator<PathArgument> it = query.getPathArguments().iterator();
216                 final PathArgument first = it.next();
217                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first,
218                     it);
219             }
220         } finally {
221             xmlWriter.close();
222         }
223     }
224
225     /**
226      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
227      * into {@link DOMResult}. Field paths are relative to parent query path.
228      *
229      * @param query      path to the root node
230      * @param result     DOM result holder
231      * @param schemaPath schema path of the parent node
232      * @param context    mountpoint schema context
233      * @param fields     list of specific fields for which the filter should be created
234      * @throws IOException        failed to write filter into {@link NormalizedNodeStreamWriter}
235      * @throws XMLStreamException failed to serialize filter into XML document
236      * @throws NullPointerException if any argument is null
237      */
238     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
239                                    final SchemaPath schemaPath, final EffectiveModelContext context,
240                                    final List<YangInstanceIdentifier> fields) throws IOException, XMLStreamException {
241         if (query.isEmpty() || fields.isEmpty()) {
242             // No query at all
243             return;
244         }
245         final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
246         final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
247
248         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
249         try {
250             try (NormalizedNodeStreamWriter streamWriter =
251                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
252                  EmptyListXmlWriter writer = new EmptyListXmlWriter(streamWriter, xmlWriter)) {
253                 final PathArgument first = rootNode.element();
254                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType())
255                         .streamToWriter(writer, first, rootNode);
256             }
257         } finally {
258             xmlWriter.close();
259         }
260     }
261
262     /**
263      * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
264      * into {@link Element}. Field paths are relative to parent query path. Filter is created without following
265      * {@link EffectiveModelContext}.
266      *
267      * @param query         path to the root node
268      * @param fields        list of specific fields for which the filter should be created
269      * @param filterElement XML filter element to which the created filter will be written
270      */
271     public static void writeSchemalessFilter(final YangInstanceIdentifier query,
272                                              final List<YangInstanceIdentifier> fields, final Element filterElement) {
273         pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
274     }
275
276     private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
277         final PathArgument pathArg = pathArgumentTree.element();
278
279         final QName nodeType = pathArg.getNodeType();
280         final String elementNamespace = nodeType.getNamespace().toString();
281
282         if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
283             // element has already been written as list key
284             return;
285         }
286
287         final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
288         data.appendChild(childElement);
289         if (pathArg instanceof NodeIdentifierWithPredicates) {
290             appendListKeyNodes(childElement, (NodeIdentifierWithPredicates) pathArg);
291         }
292         for (final PathNode childrenNode : pathArgumentTree.children()) {
293             pathArgumentTreeToXmlStructure(childrenNode, childElement);
294         }
295     }
296
297     /**
298      * Appending list key elements to parent element.
299      *
300      * @param parentElement parent XML element to which children elements are appended
301      * @param listEntryId   list entry identifier
302      */
303     public static void appendListKeyNodes(final Element parentElement, final NodeIdentifierWithPredicates listEntryId) {
304         for (Entry<QName, Object> key : listEntryId.entrySet()) {
305             final Element keyElement = parentElement.getOwnerDocument().createElementNS(
306                     key.getKey().getNamespace().toString(), key.getKey().getLocalName());
307             keyElement.setTextContent(key.getValue().toString());
308             parentElement.appendChild(keyElement);
309         }
310     }
311
312     /**
313      * Aggregation of the fields paths based on parenthesis. Only parent/enclosing {@link YangInstanceIdentifier}
314      * are kept. For example, paths '/x/y/z', '/x/y', and '/x' are aggregated into single field path: '/x'
315      *
316      * @param fields paths of fields
317      * @return filtered {@link List} of paths
318      */
319     private static List<YangInstanceIdentifier> aggregateFields(final List<YangInstanceIdentifier> fields) {
320         return fields.stream()
321                 .filter(field -> fields.stream()
322                         .filter(fieldYiid -> !field.equals(fieldYiid))
323                         .noneMatch(fieldYiid -> fieldYiid.contains(field)))
324                 .collect(Collectors.toList());
325     }
326
327     /**
328      * Construct a tree based on the parent {@link YangInstanceIdentifier} and provided list of fields. The goal of this
329      * procedure is the elimination of the redundancy that is introduced by potentially overlapping parts of the fields
330      * paths.
331      *
332      * @param query  path to parent element
333      * @param fields subpaths relative to parent path that identify specific fields
334      * @return created {@link TreeNode} structure
335      */
336     private static PathNode constructPathArgumentTree(final YangInstanceIdentifier query,
337             final List<YangInstanceIdentifier> fields) {
338         final Iterator<PathArgument> queryIterator = query.getPathArguments().iterator();
339         final PathNode rootTreeNode = new PathNode(queryIterator.next());
340
341         PathNode queryTreeNode = rootTreeNode;
342         while (queryIterator.hasNext()) {
343             queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
344         }
345
346         for (final YangInstanceIdentifier field : fields) {
347             PathNode actualFieldTreeNode = queryTreeNode;
348             for (final PathArgument fieldPathArg : field.getPathArguments()) {
349                 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
350             }
351         }
352         return rootTreeNode;
353     }
354
355     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final MountPointContext mountContext,
356             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
357         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
358
359         // FIXME: we probably need to propagate MountPointContext here and not just the child nodes
360         try (XmlParserStream xmlParserStream = XmlParserStream.create(
361                 ImmutableNormalizedNodeStreamWriter.from(resultHolder),
362                 XmlCodecFactory.create(mountContext),
363                 NodeContainerProxy.ofModelContext(NETCONF_DATA_QNAME, mountContext.getEffectiveModelContext()))) {
364             xmlParserStream.traverse(value);
365         }
366         return resultHolder;
367     }
368
369
370     // FIXME: document this interface contract. Does it support RFC8528/RFC8542? How?
371     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final EffectiveModelContext schemaContext,
372             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
373         return transformDOMSourceToNormalizedNode(new EmptyMountPointContext(schemaContext), value);
374     }
375 }