Bind operation prefix to correct namespace
[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 javax.xml.stream.XMLOutputFactory;
17 import javax.xml.stream.XMLStreamException;
18 import javax.xml.stream.XMLStreamWriter;
19 import javax.xml.transform.dom.DOMResult;
20 import javax.xml.transform.dom.DOMSource;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.netconf.api.DocumentedException;
23 import org.opendaylight.netconf.api.xml.XmlElement;
24 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
25 import org.opendaylight.netconf.api.xml.XmlUtil;
26 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
27 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
28 import org.opendaylight.yangtools.rfc7952.data.util.NormalizedMetadataWriter;
29 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
38 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
40 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
43 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.w3c.dom.Document;
50 import org.xml.sax.SAXException;
51
52 public final class NetconfUtil {
53     /**
54      * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
55      * Specifically:
56      * <ul>
57      *   <li>OpenJDK DOM writer (com.sun.xml.internal.stream.writers.XMLDOMWriterImpl) throws
58      *       UnsupportedOperationException from its setNamespaceContext() method</li>
59      *   <li>Woodstox DOM writer (com.ctc.wstx.dom.WstxDOMWrappingWriter) works with namespace context, but treats
60      *       setPrefix() calls as hints -- which are not discoverable.</li>
61      * </ul>
62      *
63      * <p>
64      * Due to this we perform a quick test for behavior and decide the appropriate strategy.
65      */
66     @FunctionalInterface
67     private interface NamespaceSetter {
68         void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
69
70         static NamespaceSetter forFactory(final XMLOutputFactory xmlFactory) {
71             final String netconfNamespace = NETCONF_QNAME.getNamespace().toString();
72             final AnyXmlNamespaceContext namespaceContext = new AnyXmlNamespaceContext(ImmutableMap.of(
73                 "op", netconfNamespace));
74
75             try {
76                 final XMLStreamWriter testWriter = xmlFactory.createXMLStreamWriter(new DOMResult(
77                     XmlUtil.newDocument()));
78                 testWriter.setNamespaceContext(namespaceContext);
79             } catch (final UnsupportedOperationException e) {
80                 // This happens with JDK's DOM writer, which we may be using
81                 LOG.warn("Unable to set namespace context, falling back to setPrefix()", e);
82                 return writer -> writer.setPrefix("op", netconfNamespace);
83             } catch (XMLStreamException e) {
84                 throw new ExceptionInInitializerError(e);
85             }
86
87             // Success, we can use setNamespaceContext()
88             return writer -> writer.setNamespaceContext(namespaceContext);
89         }
90     }
91
92     private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
93
94     // FIXME: document what exactly this QName means, as it is not referring to a tangible node nor the ietf-module.
95     // FIXME: what is this contract saying?
96     //        - is it saying all data is going to be interpreted with this root?
97     //        - is this saying we are following a specific interface contract (i.e. do we have schema mounts?)
98     //        - is it also inferring some abilities w.r.t. RFC8342?
99     public static final QName NETCONF_QNAME = QName.create(QNameModule.create(SchemaContext.NAME.getNamespace(),
100         Revision.of("2011-06-01")), "netconf").intern();
101     // FIXME: is this the device-bound revision?
102     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
103
104     public static final XMLOutputFactory XML_FACTORY;
105
106     static {
107         final XMLOutputFactory f = XMLOutputFactory.newFactory();
108         // FIXME: not repairing namespaces is probably common, this should be availabe as common XML constant.
109         f.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
110         XML_FACTORY = f;
111     }
112
113     private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
114
115     private NetconfUtil() {
116         // No-op
117     }
118
119     public static Document checkIsMessageOk(final Document response) throws DocumentedException {
120         final XmlElement docElement = XmlElement.fromDomDocument(response);
121         // FIXME: we should throw DocumentedException here
122         checkState(XmlNetconfConstants.RPC_REPLY_KEY.equals(docElement.getName()));
123         final XmlElement element = docElement.getOnlyChildElement();
124         if (XmlNetconfConstants.OK.equals(element.getName())) {
125             return response;
126         }
127
128         LOG.warn("Can not load last configuration. Operation failed.");
129         // FIXME: we should be throwing a DocumentedException here
130         throw new IllegalStateException("Can not load last configuration. Operation failed: "
131                 + XmlUtil.toString(response));
132     }
133
134     @SuppressWarnings("checkstyle:IllegalCatch")
135     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
136                                            final SchemaPath schemaPath, final SchemaContext context)
137             throws IOException, XMLStreamException {
138         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
139         try (
140              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
141                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
142              NormalizedNodeWriter normalizedNodeWriter =
143                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
144         ) {
145             normalizedNodeWriter.write(normalized);
146             normalizedNodeWriter.flush();
147         } finally {
148             try {
149                 if (writer != null) {
150                     writer.close();
151                 }
152             } catch (final Exception e) {
153                 LOG.warn("Unable to close resource properly", e);
154             }
155         }
156     }
157
158     @SuppressWarnings("checkstyle:IllegalCatch")
159     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized,
160                                            final @Nullable NormalizedMetadata metadata,
161                                            final DOMResult result, final SchemaPath schemaPath,
162                                            final SchemaContext context) throws IOException, XMLStreamException {
163         if (metadata == null) {
164             writeNormalizedNode(normalized, result, schemaPath, context);
165             return;
166         }
167
168         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
169         XML_NAMESPACE_SETTER.initializeNamespace(writer);
170         try (
171              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
172                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
173                 NormalizedMetadataWriter normalizedNodeWriter =
174                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
175         ) {
176             normalizedNodeWriter.write(normalized, metadata);
177             normalizedNodeWriter.flush();
178         } finally {
179             try {
180                 if (writer != null) {
181                     writer.close();
182                 }
183             } catch (final Exception e) {
184                 LOG.warn("Unable to close resource properly", e);
185             }
186         }
187     }
188
189     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
190             final SchemaPath schemaPath, final SchemaContext context) throws IOException, XMLStreamException {
191         if (query.isEmpty()) {
192             // No query at all
193             return;
194         }
195
196         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
197         try {
198             try (NormalizedNodeStreamWriter writer =
199                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath)) {
200                 final Iterator<PathArgument> it = query.getPathArguments().iterator();
201                 final PathArgument first = it.next();
202                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first,
203                     it);
204             }
205         } finally {
206             xmlWriter.close();
207         }
208     }
209
210     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final MountPointContext mountContext,
211             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
212         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
213         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
214         final XmlCodecFactory codecs = XmlCodecFactory.create(mountContext);
215
216         // FIXME: we probably need to propagate MountPointContext here and not just the child nodes
217         final ContainerSchemaNode dataRead = new NodeContainerProxy(NETCONF_DATA_QNAME,
218             mountContext.getSchemaContext().getChildNodes());
219         try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, codecs, dataRead)) {
220             xmlParserStream.traverse(value);
221         }
222         return resultHolder;
223     }
224
225
226     // FIXME: document this interface contract. Does it support RFC8528/RFC8542? How?
227     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final EffectiveModelContext schemaContext,
228             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
229         return transformDOMSourceToNormalizedNode(new EmptyMountPointContext(schemaContext), value);
230     }
231 }