d5ade6f283a54d59731644a801e0b4664cbdefee
[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 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;
45
46 public final class NetconfUtil {
47     /**
48      * Shim interface to handle differences around namespace handling between various XMLStreamWriter implementations.
49      * Specifically:
50      * <ul>
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>
55      * </ul>
56      *
57      * <p>
58      * Due to this we perform a quick test for behavior and decide the appropriate strategy.
59      */
60     @FunctionalInterface
61     private interface NamespaceSetter {
62         void initializeNamespace(XMLStreamWriter writer) throws XMLStreamException;
63
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));
68
69             try {
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);
79             }
80
81             // Success, we can use setNamespaceContext()
82             return writer -> writer.setNamespaceContext(namespaceContext);
83         }
84     }
85
86     private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
87
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();
91
92     public static final XMLOutputFactory XML_FACTORY;
93
94     static {
95         XML_FACTORY = XMLOutputFactory.newFactory();
96         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
97     }
98
99     private static final NamespaceSetter XML_NAMESPACE_SETTER = NamespaceSetter.forFactory(XML_FACTORY);
100
101     private NetconfUtil() {
102
103     }
104
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)) {
110             return response;
111         }
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));
115     }
116
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);
122         try (
123              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
124                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
125              NormalizedNodeWriter normalizedNodeWriter =
126                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
127         ) {
128             normalizedNodeWriter.write(normalized);
129             normalizedNodeWriter.flush();
130         } finally {
131             try {
132                 if (writer != null) {
133                     writer.close();
134                 }
135             } catch (final Exception e) {
136                 LOG.warn("Unable to close resource properly", e);
137             }
138         }
139     }
140
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);
148             return;
149         }
150
151         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
152         XML_NAMESPACE_SETTER.initializeNamespace(writer);
153         try (
154              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
155                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
156                 NormalizedMetadataWriter normalizedNodeWriter =
157                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
158         ) {
159             normalizedNodeWriter.write(normalized, metadata);
160             normalizedNodeWriter.flush();
161         } finally {
162             try {
163                 if (writer != null) {
164                     writer.close();
165                 }
166             } catch (final Exception e) {
167                 LOG.warn("Unable to close resource properly", e);
168             }
169         }
170     }
171
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()) {
175             // No query at all
176             return;
177         }
178
179         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
180         try {
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,
186                     it);
187             }
188         } finally {
189             xmlWriter.close();
190         }
191     }
192
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);
201         }
202         return resultHolder;
203     }
204 }