Merge "Clean up netconf-parent root pom"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / 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.netconf.sal.connect.netconf.schema.mapping;
9
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
13
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.io.IOException;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Date;
22 import java.util.Map;
23 import javax.annotation.Nonnull;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.transform.dom.DOMResult;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
28 import org.opendaylight.controller.config.util.xml.XmlElement;
29 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
30 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
32 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
35 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
36 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.Revision;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57
58 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
59
60     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
61
62     private final SchemaContext schemaContext;
63     private final BaseSchema baseSchema;
64     private final MessageCounter counter;
65     private final Map<QName, RpcDefinition> mappedRpcs;
66     private final Multimap<QName, NotificationDefinition> mappedNotifications;
67
68     private final boolean strictParsing;
69
70     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
71         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
72     }
73
74     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
75                                      final BaseSchema baseSchema) {
76         this.counter = new MessageCounter();
77         this.schemaContext = schemaContext;
78         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
79         mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
80             node -> node.getQName().withoutRevision());
81         this.baseSchema = baseSchema;
82         this.strictParsing = strictParsing;
83     }
84
85     @SuppressWarnings("checkstyle:IllegalCatch")
86     @Override
87     public synchronized DOMNotification toNotification(final NetconfMessage message) {
88         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
89         final QName notificationNoRev;
90         try {
91             notificationNoRev = QName.create(
92                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
93         } catch (final MissingNameSpaceException e) {
94             throw new IllegalArgumentException(
95                     "Unable to parse notification " + message + ", cannot find namespace", e);
96         }
97         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
98         Preconditions.checkArgument(notificationDefinitions.size() > 0,
99                 "Unable to parse notification %s, unknown notification. Available notifications: %s",
100                 notificationDefinitions, mappedNotifications.keySet());
101
102         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
103
104         final ContainerSchemaNode notificationAsContainerSchemaNode =
105                 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
106
107         final Element element = stripped.getValue().getDomElement();
108         final ContainerNode content;
109         try {
110             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
111             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
112             final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
113                     notificationAsContainerSchemaNode, strictParsing);
114             xmlParser.traverse(new DOMSource(element));
115             content = (ContainerNode) resultHolder.getResult();
116         } catch (final Exception e) {
117             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
118         }
119         return new NetconfDeviceNotification(content, stripped.getKey());
120     }
121
122     private static NotificationDefinition getMostRecentNotification(
123             final Collection<NotificationDefinition> notificationDefinitions) {
124         return Collections.max(notificationDefinitions, (o1, o2) ->
125             Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
126     }
127
128     @Override
129     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
130         // In case no input for rpc is defined, we can simply construct the payload here
131         final QName rpcQName = rpc.getLastComponent();
132         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
133
134         // Determine whether a base netconf operation is being invoked
135         // and also check if the device exposed model for base netconf.
136         // If no, use pre built base netconf operations model
137         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
138         if (needToUseBaseCtx) {
139             currentMappedRpcs = baseSchema.getMappedRpcs();
140         }
141
142         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
143                 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
144         if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
145             return new NetconfMessage(NetconfMessageTransformUtil
146                     .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
147         }
148
149         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
150         Preconditions.checkArgument(payload instanceof ContainerNode,
151                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
152
153         // Set the path to the input of rpc for the node stream writer
154         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
155         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
156
157         try {
158             // If the schema context for netconf device does not contain model for base netconf operations,
159             // use default pre build context with just the base model
160             // This way operations like lock/unlock are supported even if the source for base model was not provided
161             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
162             NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpc, ctx);
163         } catch (final XMLStreamException | IOException | IllegalStateException e) {
164             throw new IllegalStateException("Unable to serialize " + rpc, e);
165         }
166
167         final Document node = result.getNode().getOwnerDocument();
168
169         return new NetconfMessage(node);
170     }
171
172     private static boolean isBaseOrNotificationRpc(final QName rpc) {
173         return rpc.getNamespace().equals(NETCONF_URI)
174                 || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
175                 || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
176     }
177
178     @SuppressWarnings("checkstyle:IllegalCatch")
179     @Override
180     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
181         final NormalizedNode<?, ?> normalizedNode;
182         final QName rpcQName = rpc.getLastComponent();
183         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
184             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
185             final ContainerSchemaNode schemaForDataRead =
186                     NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
187             final ContainerNode dataNode;
188
189             try {
190                 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
191                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
192                 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext, schemaForDataRead,
193                         strictParsing);
194                 xmlParser.traverse(new DOMSource(xmlData));
195                 dataNode = (ContainerNode) resultHolder.getResult();
196             } catch (final Exception e) {
197                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
198             }
199
200             normalizedNode = Builders.containerBuilder()
201                     .withNodeIdentifier(new YangInstanceIdentifier
202                             .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
203                     .withChild(dataNode).build();
204         } else {
205
206             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
207
208             // Determine whether a base netconf operation is being invoked
209             // and also check if the device exposed model for base netconf.
210             // If no, use pre built base netconf operations model
211             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
212             if (needToUseBaseCtx) {
213                 currentMappedRpcs = baseSchema.getMappedRpcs();
214             }
215
216             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
217             Preconditions.checkArgument(rpcDefinition != null,
218                     "Unable to parse response of %s, the rpc is unknown", rpcQName);
219
220             // In case no input for rpc is defined, we can simply construct the payload here
221             if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
222                 Preconditions.checkArgument(XmlElement.fromDomDocument(
223                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
224                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
225                 normalizedNode = null;
226             } else {
227                 final Element element = message.getDocument().getDocumentElement();
228                 try {
229                     final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
230                     final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
231                     final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
232                             rpcDefinition.getOutput(), strictParsing);
233                     xmlParser.traverse(new DOMSource(element));
234                     normalizedNode = resultHolder.getResult();
235                 } catch (final Exception e) {
236                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
237                 }
238             }
239         }
240         return new DefaultDOMRpcResult(normalizedNode);
241     }
242
243     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
244         private final ContainerNode content;
245         private final SchemaPath schemaPath;
246         private final Date eventTime;
247
248         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
249             this.content = content;
250             this.eventTime = eventTime;
251             this.schemaPath = toPath(content.getNodeType());
252         }
253
254         @Nonnull
255         @Override
256         public SchemaPath getType() {
257             return schemaPath;
258
259         }
260
261         @Nonnull
262         @Override
263         public ContainerNode getBody() {
264             return content;
265         }
266
267         @Override
268         public Date getEventTime() {
269             return eventTime;
270         }
271     }
272 }