217f106df265d226478b062ce4a87d80b96d5314
[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 java.io.IOException;
12 import java.net.URISyntaxException;
13 import java.util.Iterator;
14 import javax.xml.stream.XMLOutputFactory;
15 import javax.xml.stream.XMLStreamException;
16 import javax.xml.stream.XMLStreamWriter;
17 import javax.xml.transform.dom.DOMResult;
18 import javax.xml.transform.dom.DOMSource;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.netconf.api.DocumentedException;
21 import org.opendaylight.netconf.api.xml.XmlElement;
22 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
23 import org.opendaylight.netconf.api.xml.XmlUtil;
24 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
25 import org.opendaylight.yangtools.rfc7952.data.util.NormalizedMetadataWriter;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
31 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
32 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
34 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
35 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
36 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Document;
43 import org.xml.sax.SAXException;
44
45 public final class NetconfUtil {
46
47     public static final QName NETCONF_QNAME =
48             QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
49     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
50     public static final XMLOutputFactory XML_FACTORY;
51
52     private static final Logger LOG = LoggerFactory.getLogger(NetconfUtil.class);
53
54     static {
55         XML_FACTORY = XMLOutputFactory.newFactory();
56         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
57     }
58
59     private NetconfUtil() {}
60
61     public static Document checkIsMessageOk(final Document response) throws DocumentedException {
62         XmlElement element = XmlElement.fromDomDocument(response);
63         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
64         element = element.getOnlyChildElement();
65         if (element.getName().equals(XmlNetconfConstants.OK)) {
66             return response;
67         }
68         LOG.warn("Can not load last configuration. Operation failed.");
69         throw new IllegalStateException("Can not load last configuration. Operation failed: "
70                 + XmlUtil.toString(response));
71     }
72
73     @SuppressWarnings("checkstyle:IllegalCatch")
74     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
75                                            final SchemaPath schemaPath, final SchemaContext context)
76             throws IOException, XMLStreamException {
77         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
78         try (
79              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
80                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
81              NormalizedNodeWriter normalizedNodeWriter =
82                      NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
83         ) {
84             normalizedNodeWriter.write(normalized);
85             normalizedNodeWriter.flush();
86         } finally {
87             try {
88                 if (writer != null) {
89                     writer.close();
90                 }
91             } catch (final Exception e) {
92                 LOG.warn("Unable to close resource properly", e);
93             }
94         }
95     }
96
97     @SuppressWarnings("checkstyle:IllegalCatch")
98     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized,
99                                            final @Nullable NormalizedMetadata metadata,
100                                            final DOMResult result, final SchemaPath schemaPath,
101                                            final SchemaContext context) throws IOException, XMLStreamException {
102         if (metadata == null) {
103             writeNormalizedNode(normalized, result, schemaPath, context);
104             return;
105         }
106
107         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
108         try (
109              NormalizedNodeStreamWriter normalizedNodeStreamWriter =
110                      XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
111                 NormalizedMetadataWriter normalizedNodeWriter =
112                      NormalizedMetadataWriter.forStreamWriter(normalizedNodeStreamWriter)
113         ) {
114             normalizedNodeWriter.write(normalized, metadata);
115             normalizedNodeWriter.flush();
116         } finally {
117             try {
118                 if (writer != null) {
119                     writer.close();
120                 }
121             } catch (final Exception e) {
122                 LOG.warn("Unable to close resource properly", e);
123             }
124         }
125     }
126
127     public static void writeFilter(final YangInstanceIdentifier query, final DOMResult result,
128             final SchemaPath schemaPath, final SchemaContext context) throws IOException, XMLStreamException {
129         if (query.isEmpty()) {
130             // No query at all
131             return;
132         }
133
134         final XMLStreamWriter xmlWriter = XML_FACTORY.createXMLStreamWriter(result);
135         try {
136             try (NormalizedNodeStreamWriter writer =
137                     XMLStreamNormalizedNodeStreamWriter.create(xmlWriter, context, schemaPath)) {
138                 final Iterator<PathArgument> it = query.getPathArguments().iterator();
139                 final PathArgument first = it.next();
140                 StreamingContext.fromSchemaAndQNameChecked(context, first.getNodeType()).streamToWriter(writer, first,
141                     it);
142             }
143         } finally {
144             xmlWriter.close();
145         }
146     }
147
148     public static NormalizedNodeResult transformDOMSourceToNormalizedNode(final SchemaContext schemaContext,
149             final DOMSource value) throws XMLStreamException, URISyntaxException, IOException, SAXException {
150         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
151         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
152         final XmlCodecFactory codecs = XmlCodecFactory.create(schemaContext);
153         final ContainerSchemaNode dataRead = new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
154         try (XmlParserStream xmlParserStream = XmlParserStream.create(writer, codecs, dataRead)) {
155             xmlParserStream.traverse(value);
156         }
157         return resultHolder;
158     }
159 }