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 com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import java.io.IOException;
13 import java.net.URISyntaxException;
14 import java.util.Iterator;
15 import javax.xml.stream.XMLOutputFactory;
16 import javax.xml.stream.XMLStreamException;
17 import javax.xml.stream.XMLStreamWriter;
18 import javax.xml.transform.dom.DOMResult;
19 import javax.xml.transform.dom.DOMSource;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.netconf.api.DocumentedException;
22 import org.opendaylight.netconf.api.xml.XmlElement;
23 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
24 import org.opendaylight.netconf.api.xml.XmlUtil;
25 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
26 import org.opendaylight.yangtools.rfc7952.data.util.NormalizedMetadataWriter;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
33 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
34 import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
35 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.xml.sax.SAXException;
46 public final class NetconfUtil {
48 * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
51 * <li>OpenJDK DOM writer (com.sun.xml.internal.stream.writers.XMLDOMWriterImpl) throws
52 * UnsupportedOperationException from its setNamespaceContext() method</li>
53 * <li>Woodstox DOM writer (com.ctc.wstx.dom.WstxDOMWrappingWriter) works with namespace context, but treats
54 * setPrefix() calls as hints -- which are not discoverable.</li>
58 * Due to this we perform a quick test for behavior and decide the appropriate strategy.
61 private interface NamespaceSetter {
62 void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
64 static NamespaceSetter forFactory(final XMLOutputFactory xmlFactory) {
65 final String netconfNamespace = NETCONF_QNAME.getNamespace().toString();
66 final AnyXmlNamespaceContext namespaceContext = new AnyXmlNamespaceContext(ImmutableMap.of(
67 "op", netconfNamespace));
70 final XMLStreamWriter testWriter = xmlFactory.createXMLStreamWriter(new DOMResult(
71 XmlUtil.newDocument()));
72 testWriter.setNamespaceContext(namespaceContext);
73 } catch (final UnsupportedOperationException e) {
74 // This happens with JDK's DOM writer, which we may be using
75 LOG.warn("Unable to set namespace context, falling back to setPrefix()", e);
76 return writer -> writer.setPrefix("op", netconfNamespace);
77 } catch (XMLStreamException e) {
78 throw new ExceptionInInitializerError(e);
81 // Success, we can use setNamespaceContext()
82 return writer -> writer.setNamespaceContext(namespaceContext);
86 private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
88 public static final QName NETCONF_QNAME =
89 QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
90 public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
92 public static final XMLOutputFactory XML_FACTORY;
95 XML_FACTORY = XMLOutputFactory.newFactory();
96 XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
99 private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
101 private NetconfUtil() {
105 public static Document checkIsMessageOk(final Document response) throws DocumentedException {
106 XmlElement element = XmlElement.fromDomDocument(response);
107 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
108 element = element.getOnlyChildElement();
109 if (element.getName().equals(XmlNetconfConstants.OK)) {
112 LOG.warn("Can not load last configuration. Operation failed.");
113 throw new IllegalStateException("Can not load last configuration. Operation failed: "
114 + XmlUtil.toString(response));
117 @SuppressWarnings("checkstyle:IllegalCatch")
118 public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
119 final SchemaPath schemaPath, final SchemaContext context)
120 throws IOException, XMLStreamException {
121 final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
123 NormalizedNodeStreamWriter normalizedNodeStreamWriter =
124 XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
125 NormalizedNodeWriter normalizedNodeWriter =
126 NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
128 normalizedNodeWriter.write(normalized);
129 normalizedNodeWriter.flush();
132 if (writer != null) {
135 } catch (final Exception e) {
136 LOG.warn("Unable to close resource properly", e);
141 @SuppressWarnings("checkstyle:IllegalCatch")
142 public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized,
143 final @Nullable NormalizedMetadata metadata,
144 final DOMResult result, final SchemaPath schemaPath,
145 final SchemaContext context) throws IOException, XMLStreamException {
146 if (metadata == null) {
147 writeNormalizedNode(normalized, result, schemaPath, context);
151 final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
152 XML_NAMESPACE_SETTER.initializeNamespace(writer);
154 NormalizedNodeStreamWriter normalizedNodeStreamWriter =
155 XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
156 NormalizedMetadataWriter normalizedNodeWriter =
157 NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
159 normalizedNodeWriter.write(normalized, metadata);
160 normalizedNodeWriter.flush();
163 if (writer != null) {
166 } catch (final Exception e) {
167 LOG.warn("Unable to close resource properly", e);
172 public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
173 final SchemaPath schemaPath, final SchemaContext context) throws IOException, XMLStreamException {
174 if (query.isEmpty()) {
179 final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
181 try (NormalizedNodeStreamWriter writer =
182 XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath)) {
183 final Iterator<PathArgument> it = query.getPathArguments().iterator();
184 final PathArgument first = it.next();
185 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first,
193 public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final SchemaContext schemaContext,
194 final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
195 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
196 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
197 final XmlCodecFactory codecs = XmlCodecFactory.create(schemaContext);
198 final ContainerSchemaNode dataRead = new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
199 try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, codecs, dataRead)) {
200 xmlParserStream.traverse(value);