2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.util;
10 import static com.google.common.base.Preconditions.checkState;
12 import java.io.IOException;
13 import java.net.URISyntaxException;
14 import java.util.Iterator;
15 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.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;
56 public final class NetconfUtil {
58 * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
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>
68 * Due to this we perform a quick test for behavior and decide the appropriate strategy.
71 private interface NamespaceSetter {
72 void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
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));
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);
90 // Success, we can use setNamespaceContext()
91 return writer -> writer.setNamespaceContext(namespaceContext);
95 private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
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();
107 public static final XMLOutputFactory XML_FACTORY;
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);
116 private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
118 private NetconfUtil() {
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())) {
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));
138 * Write {@code normalized} data into {@link DOMResult}.
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
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);
151 NormalizedNodeStreamWriter normalizedNodeStreamWriter =
152 XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
153 NormalizedNodeWriter normalizedNodeWriter =
154 NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
156 normalizedNodeWriter.write(normalized);
157 normalizedNodeWriter.flush();
164 * Write {@code normalized} data along with corresponding {@code metadata} into {@link DOMResult}.
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
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);
182 final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
183 XML_NAMESPACE_SETTER.initializeNamespace(writer);
185 NormalizedNodeStreamWriter normalizedNodeStreamWriter =
186 XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
187 NormalizedMetadataWriter normalizedNodeWriter =
188 NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
190 normalizedNodeWriter.write(normalized, metadata);
191 normalizedNodeWriter.flush();
198 * Write data specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
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
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);
223 * Write data specified by {@link YangInstanceIdentifier} along with corresponding {@code metadata}
224 * into {@link DOMResult}.
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
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);
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);
257 * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
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
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()) {
273 final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
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,
289 * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
290 * into {@link DOMResult}. Field paths are relative to parent query path.
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
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()) {
308 final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
309 final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
311 final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
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);
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}.
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
334 public static void writeSchemalessFilter(final YangInstanceIdentifier query,
335 final List<YangInstanceIdentifier> fields, final Element filterElement) {
336 pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
339 private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
340 final PathArgument pathArg = pathArgumentTree.element();
342 final QName nodeType = pathArg.getNodeType();
343 final String elementNamespace = nodeType.getNamespace().toString();
345 if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
346 // element has already been written as list key
350 final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
351 data.appendChild(childElement);
352 if (pathArg instanceof NodeIdentifierWithPredicates) {
353 appendListKeyNodes(childElement, (NodeIdentifierWithPredicates) pathArg);
355 for (final PathNode childrenNode : pathArgumentTree.children()) {
356 pathArgumentTreeToXmlStructure(childrenNode, childElement);
361 * Appending list key elements to parent element.
363 * @param parentElement parent XML element to which children elements are appended
364 * @param listEntryId list entry identifier
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);
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'
379 * @param fields paths of fields
380 * @return filtered {@link List} of paths
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());
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
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
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());
404 PathNode queryTreeNode = rootTreeNode;
405 while (queryIterator.hasNext()) {
406 queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
409 for (final YangInstanceIdentifier field : fields) {
410 PathNode actualFieldTreeNode = queryTreeNode;
411 for (final PathArgument fieldPathArg : field.getPathArguments()) {
412 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
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);
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);