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 xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
150 try (var streamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath);
151 var writer = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
152 writer.write(normalized);
160 * Write {@code normalized} data along with corresponding {@code metadata} into {@link DOMResult}.
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
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);
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);
190 * Write data specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
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
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);
214 * Write data specified by {@link YangInstanceIdentifier} along with corresponding {@code metadata}
215 * into {@link DOMResult}.
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
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);
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);
247 * Writing subtree filter specified by {@link YangInstanceIdentifier} into {@link DOMResult}.
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
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()) {
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);
275 * Writing subtree filter specified by parent {@link YangInstanceIdentifier} and specific fields
276 * into {@link DOMResult}. Field paths are relative to parent query path.
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
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()) {
295 final List<YangInstanceIdentifier> aggregatedFields = aggregateFields(fields);
296 final PathNode rootNode = constructPathArgumentTree(query, aggregatedFields);
298 final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
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);
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}.
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
320 public static void writeSchemalessFilter(final YangInstanceIdentifier query,
321 final List<YangInstanceIdentifier> fields, final Element filterElement) {
322 pathArgumentTreeToXmlStructure(constructPathArgumentTree(query, aggregateFields(fields)), filterElement);
325 private static void pathArgumentTreeToXmlStructure(final PathNode pathArgumentTree, final Element data) {
326 final PathArgument pathArg = pathArgumentTree.element();
328 final QName nodeType = pathArg.getNodeType();
329 final String elementNamespace = nodeType.getNamespace().toString();
331 if (data.getElementsByTagNameNS(elementNamespace, nodeType.getLocalName()).getLength() != 0) {
332 // element has already been written as list key
336 final Element childElement = data.getOwnerDocument().createElementNS(elementNamespace, nodeType.getLocalName());
337 data.appendChild(childElement);
338 if (pathArg instanceof NodeIdentifierWithPredicates) {
339 appendListKeyNodes(childElement, (NodeIdentifierWithPredicates) pathArg);
341 for (final PathNode childrenNode : pathArgumentTree.children()) {
342 pathArgumentTreeToXmlStructure(childrenNode, childElement);
347 * Appending list key elements to parent element.
349 * @param parentElement parent XML element to which children elements are appended
350 * @param listEntryId list entry identifier
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);
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'
365 * @param fields paths of fields
366 * @return filtered {@link List} of paths
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());
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
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
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());
390 PathNode queryTreeNode = rootTreeNode;
391 while (queryIterator.hasNext()) {
392 queryTreeNode = queryTreeNode.ensureChild(queryIterator.next());
395 for (final YangInstanceIdentifier field : fields) {
396 PathNode actualFieldTreeNode = queryTreeNode;
397 for (final PathArgument fieldPathArg : field.getPathArguments()) {
398 actualFieldTreeNode = actualFieldTreeNode.ensureChild(fieldPathArg);
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);
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);