Migrate users of AnyXml node to DOMSource
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / schema / mapping / NetconfMessageTransformer.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.connect.netconf.schema.mapping;
9
10 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RPC_QNAME;
11
12 import com.google.common.base.Function;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Multimap;
19 import com.google.common.collect.Multimaps;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.NoSuchElementException;
26 import java.util.Set;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.stream.XMLStreamWriter;
29 import javax.xml.transform.dom.DOMResult;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
31 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
34 import org.opendaylight.controller.netconf.util.xml.XmlElement;
35 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
36 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
37 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
38 import org.opendaylight.controller.sal.connect.util.MessageCounter;
39 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
47 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
49 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
50 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Document;
60 import org.w3c.dom.Element;
61
62 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
63
64     public static final String MESSAGE_ID_PREFIX = "m";
65
66     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformer.class);
67
68     private static final DomToNormalizedNodeParserFactory NORMALIZED_NODE_PARSER_FACTORY = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER);
69
70     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
71         @Override
72         public QName apply(final SchemaNode rpcDefinition) {
73             return rpcDefinition.getQName();
74         }
75     };
76
77     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
78         @Override
79         public QName apply(final SchemaNode notification) {
80             return QNAME_FUNCTION.apply(notification).withoutRevision();
81         }
82     };
83     private static final SchemaContext BASE_NETCONF_CTX;
84
85     static {
86         try {
87             final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
88             // TODO this should be used only if the base is not present
89             moduleInfoBackedContext.addModuleInfos(
90                     Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
91             BASE_NETCONF_CTX = moduleInfoBackedContext.tryToCreateSchemaContext().get();
92         } catch (final RuntimeException e) {
93             LOG.error("Unable to prepare schema context for base netconf ops", e);
94             throw new ExceptionInInitializerError(e);
95         }
96     }
97
98     private final SchemaContext schemaContext;
99     private final MessageCounter counter;
100     private final Map<QName, RpcDefinition> mappedRpcs;
101     private final Multimap<QName, NotificationDefinition> mappedNotifications;
102
103     public NetconfMessageTransformer(final SchemaContext schemaContext) {
104         this.counter = new MessageCounter();
105         this.schemaContext = schemaContext;
106
107         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
108         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
109     }
110
111     @Override
112     public synchronized ContainerNode toNotification(final NetconfMessage message) {
113         final XmlElement stripped = stripNotification(message);
114         final QName notificationNoRev;
115         try {
116             // How to construct QName with no revision ?
117             notificationNoRev = QName.cachedReference(QName.create(stripped.getNamespace(), "0000-00-00", stripped.getName()).withoutRevision());
118         } catch (final MissingNameSpaceException e) {
119             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
120         }
121
122         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
123         Preconditions.checkArgument(notificationDefinitions.size() > 0,
124                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
125
126         // FIXME if multiple revisions for same notifications are present, we should pick the most recent. Or ?
127         // We should probably just put the most recent notification versions into our map. We can expect that the device sends the data according to the latest available revision of a model.
128         final NotificationDefinition next = notificationDefinitions.iterator().next();
129
130         // We wrap the notification as a container node in order to reuse the parsers and builders for container node
131         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(next);
132         return NORMALIZED_NODE_PARSER_FACTORY.getContainerNodeParser().parse(Collections.singleton(stripped.getDomElement()), notificationAsContainerSchemaNode);
133     }
134
135     // FIXME move somewhere to util
136     private static XmlElement stripNotification(final NetconfMessage message) {
137         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
138         final List<XmlElement> childElements = xmlElement.getChildElements();
139         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format", message);
140         try {
141             return Iterables.find(childElements, new Predicate<XmlElement>() {
142                 @Override
143                 public boolean apply(final XmlElement xmlElement) {
144                     return !xmlElement.getName().equals("eventTime");
145                 }
146             });
147         } catch (final NoSuchElementException e) {
148             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot strip notification metadata", e);
149         }
150     }
151
152     @Override
153     public NetconfMessage toRpcRequest(SchemaPath rpc, final ContainerNode payload) {
154         // In case no input for rpc is defined, we can simply construct the payload here
155         final QName rpcQName = rpc.getLastComponent();
156         Preconditions.checkNotNull(mappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, mappedRpcs.keySet());
157         if(mappedRpcs.get(rpcQName).getInput() == null) {
158             final Document document = XmlUtil.newDocument();
159             final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
160             document.appendChild(elementNS);
161             return new NetconfMessage(document);
162         }
163
164         // Set the path to the input of rpc for the node stream writer
165         rpc = rpc.createChild(QName.cachedReference(QName.create(rpcQName, "input")));
166         final DOMResult result = prepareDomResultForRpcRequest(rpcQName);
167
168         try {
169             writeNormalizedRpc(payload, result, rpc, schemaContext);
170         } catch (final XMLStreamException | IOException | IllegalStateException e) {
171             throw new IllegalStateException("Unable to serialize " + rpc, e);
172         }
173
174         final Document node = result.getNode().getOwnerDocument();
175
176         node.getDocumentElement().setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
177         return new NetconfMessage(node);
178     }
179
180     private DOMResult prepareDomResultForRpcRequest(final QName rpcQName) {
181         final Document document = XmlUtil.newDocument();
182         final Element rpcNS = document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
183         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
184         rpcNS.appendChild(elementNS);
185         document.appendChild(rpcNS);
186         return new DOMResult(elementNS);
187     }
188
189     private void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
190         final NormalizedNodeWriter normalizedNodeWriter;
191         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
192         XMLStreamWriter writer = null;
193         try {
194             writer = NetconfMessageTransformUtil.XML_FACTORY.createXMLStreamWriter(result);
195             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath);
196             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
197
198             for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> editElement : normalized.getValue()) {
199                 normalizedNodeWriter.write(editElement);
200             }
201             normalizedNodeWriter.flush();
202         } finally {
203             try {
204                 if(normalizedNodeStreamWriter != null) {
205                     normalizedNodeStreamWriter.close();
206                 }
207                 if(writer != null) {
208                     writer.close();
209                 }
210             } catch (final Exception e) {
211                 LOG.warn("Unable to close resource properly", e);
212             }
213         }
214     }
215
216     @Override
217     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
218         final NormalizedNode<?, ?> normalizedNode;
219         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpc.getLastComponent())) {
220             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
221             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
222             final ContainerNode dataNode = NORMALIZED_NODE_PARSER_FACTORY.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
223
224             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
225                     .withChild(dataNode).build();
226         } else {
227             final Set<Element> documentElement = Collections.singleton(message.getDocument().getDocumentElement());
228             final RpcDefinition rpcDefinition = mappedRpcs.get(rpc.getLastComponent());
229             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpc.getLastComponent());
230
231             // In case no input for rpc is defined, we can simply construct the payload here
232             if (rpcDefinition.getOutput() == null) {
233                 Preconditions.checkArgument(XmlElement.fromDomDocument(message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
234                         "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
235                 normalizedNode = null;
236             } else {
237                 normalizedNode = NORMALIZED_NODE_PARSER_FACTORY.getContainerNodeParser().parse(documentElement, rpcDefinition.getOutput());
238             }
239         }
240         return new DefaultDOMRpcResult(normalizedNode);
241     }
242
243 }