Eliminate use of SchemaNode.getPath() in sal-netconf-connector
[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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
14
15 import com.google.common.annotations.Beta;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Preconditions;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Multimap;
23 import com.google.common.collect.Multimaps;
24 import com.google.common.collect.Streams;
25 import java.io.IOException;
26 import java.net.URISyntaxException;
27 import java.time.Instant;
28 import java.util.AbstractMap;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Optional;
37 import java.util.Set;
38 import java.util.function.Function;
39 import java.util.stream.Collectors;
40 import javax.xml.stream.XMLStreamException;
41 import javax.xml.transform.dom.DOMResult;
42 import javax.xml.transform.dom.DOMSource;
43 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
44 import org.opendaylight.mdsal.dom.api.DOMActionResult;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
46 import org.opendaylight.mdsal.dom.api.DOMEvent;
47 import org.opendaylight.mdsal.dom.api.DOMNotification;
48 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
49 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
50 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
51 import org.opendaylight.netconf.api.NetconfMessage;
52 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
53 import org.opendaylight.netconf.api.xml.XmlElement;
54 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
55 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
56 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
57 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.common.Revision;
60 import org.opendaylight.yangtools.yang.common.XMLNamespace;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
68 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
71 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
73 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
74 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
75 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
79 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
81 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.Module;
84 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
85 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
86 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
87 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
88 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
90 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
91 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
94 import org.w3c.dom.Document;
95 import org.w3c.dom.Element;
96 import org.w3c.dom.Node;
97 import org.w3c.dom.NodeList;
98 import org.xml.sax.SAXException;
99
100 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
101     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
102
103     private static final ImmutableSet<XMLNamespace> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
104         NETCONF_URI,
105         IETF_NETCONF_NOTIFICATIONS.getNamespace(),
106         CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
107
108     private final MountPointContext mountContext;
109     private final DataSchemaContextTree contextTree;
110     private final BaseSchema baseSchema;
111     private final MessageCounter counter;
112     private final ImmutableMap<QName, ? extends RpcDefinition> mappedRpcs;
113     private final Multimap<QName, ? extends NotificationDefinition> mappedNotifications;
114     private final boolean strictParsing;
115     private final ImmutableMap<Absolute, ActionDefinition> actions;
116
117     public NetconfMessageTransformer(final MountPointContext mountContext, final boolean strictParsing,
118                                      final BaseSchema baseSchema) {
119         this.counter = new MessageCounter();
120         this.mountContext = requireNonNull(mountContext);
121
122         final EffectiveModelContext schemaContext = mountContext.getEffectiveModelContext();
123         this.contextTree = DataSchemaContextTree.from(schemaContext);
124
125         this.mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
126         this.actions = getActions(schemaContext);
127
128         // RFC6020 normal notifications
129         this.mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
130             node -> node.getQName().withoutRevision());
131         this.baseSchema = baseSchema;
132         this.strictParsing = strictParsing;
133     }
134
135     @VisibleForTesting
136     static ImmutableMap<Absolute, ActionDefinition> getActions(final SchemaContext schemaContext) {
137         final Map<Absolute, ActionDefinition> values = new HashMap<>();
138         final SchemaInferenceStack stack = SchemaInferenceStack.of((EffectiveModelContext) schemaContext);
139         findAction(schemaContext, values, stack);
140         return ImmutableMap.copyOf(values);
141     }
142
143     private static void findAction(final DataSchemaNode dataSchemaNode, final Map<Absolute, ActionDefinition> builder,
144                                    final SchemaInferenceStack stack) {
145         if (dataSchemaNode instanceof ActionNodeContainer) {
146             for (ActionDefinition actionDefinition : ((ActionNodeContainer) dataSchemaNode).getActions()) {
147                 stack.enterSchemaTree(actionDefinition.getQName());
148                 builder.put(stack.toSchemaNodeIdentifier(), actionDefinition);
149                 stack.exit();
150             }
151         }
152         if (dataSchemaNode instanceof DataNodeContainer) {
153             for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
154                 stack.enterSchemaTree(innerDataSchemaNode.getQName());
155                 findAction(innerDataSchemaNode, builder, stack);
156                 stack.exit();
157             }
158         } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
159             for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases()) {
160                 stack.enterSchemaTree(caze.getQName());
161                 findAction(caze, builder, stack);
162                 stack.exit();
163             }
164         }
165     }
166
167     @Override
168     public synchronized DOMNotification toNotification(final NetconfMessage message) {
169         final Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
170         final QName notificationNoRev;
171         try {
172             notificationNoRev = QName.create(
173                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
174         } catch (final MissingNameSpaceException e) {
175             throw new IllegalArgumentException(
176                     "Unable to parse notification " + message + ", cannot find namespace", e);
177         }
178
179         Collection<? extends NotificationDefinition> notificationDefinitions =
180                 mappedNotifications.get(notificationNoRev);
181         Element element = stripped.getValue().getDomElement();
182
183         NestedNotificationInfo nestedNotificationInfo = null;
184         if (notificationDefinitions.isEmpty()) {
185             // check if notification is nested notification
186             Optional<NestedNotificationInfo> nestedNotificationOptional = findNestedNotification(message, element);
187             if (nestedNotificationOptional.isPresent()) {
188                 nestedNotificationInfo = nestedNotificationOptional.get();
189                 notificationDefinitions = Collections.singletonList(nestedNotificationInfo.notificationDefinition);
190                 element = (Element) nestedNotificationInfo.notificationNode;
191             }
192         }
193         Preconditions.checkArgument(notificationDefinitions.size() > 0,
194                 "Unable to parse notification %s, unknown notification. Available notifications: %s",
195                 notificationDefinitions, mappedNotifications.keySet());
196
197         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
198
199         final ContainerNode content;
200         final SchemaInferenceStack stack;
201         final List<QName> qnames;
202         if (nestedNotificationInfo != null) {
203             qnames = nestedNotificationInfo.domDataTreeIdentifier.getRootIdentifier().getPathArguments().stream()
204                     .filter(arg -> !(arg instanceof NodeIdentifierWithPredicates))
205                     .filter(arg -> !(arg instanceof AugmentationIdentifier))
206                     .map(PathArgument::getNodeType)
207                     .map(qName -> QName.create(mostRecentNotification.getQName(), qName.getLocalName()))
208                     .collect(Collectors.toList());
209             stack = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), Absolute.of(qnames));
210         } else {
211             stack = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(),
212                     Absolute.of(mostRecentNotification.getQName()));
213         }
214
215         try {
216             final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
217             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
218             final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
219                     stack.toInference(), strictParsing);
220             xmlParser.traverse(new DOMSource(element));
221             content = (ContainerNode) resultHolder.getResult();
222         } catch (XMLStreamException | URISyntaxException | IOException | SAXException
223                 | UnsupportedOperationException e) {
224             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
225         }
226
227         if (nestedNotificationInfo != null) {
228             return new NetconfDeviceTreeNotification(content,
229                 stack.toSchemaNodeIdentifier(),
230                 stripped.getKey(), nestedNotificationInfo.domDataTreeIdentifier);
231         }
232
233         return new NetconfDeviceNotification(content, stripped.getKey());
234     }
235
236     private Optional<NestedNotificationInfo> findNestedNotification(final NetconfMessage message,
237             final Element element) {
238         final Iterator<? extends Module> modules = mountContext.getEffectiveModelContext()
239                 .findModules(XMLNamespace.of(element.getNamespaceURI())).iterator();
240         if (!modules.hasNext()) {
241             throw new IllegalArgumentException(
242                     "Unable to parse notification " + message + ", cannot find top level module");
243         }
244         final Module module = modules.next();
245         final QName topLevelNodeQName = QName.create(element.getNamespaceURI(), element.getLocalName());
246         for (DataSchemaNode childNode : module.getChildNodes()) {
247             if (topLevelNodeQName.isEqualWithoutRevision(childNode.getQName())) {
248                 return Optional.of(traverseXmlNodeContainingNotification(element, childNode,
249                     YangInstanceIdentifier.builder()));
250             }
251         }
252         return Optional.empty();
253     }
254
255     private NestedNotificationInfo traverseXmlNodeContainingNotification(final Node xmlNode,
256             final SchemaNode schemaNode, final YangInstanceIdentifier.InstanceIdentifierBuilder builder) {
257         if (schemaNode instanceof ContainerSchemaNode) {
258             ContainerSchemaNode dataContainerNode = (ContainerSchemaNode) schemaNode;
259             builder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
260
261             Entry<Node, SchemaNode> xmlContainerChildPair = findXmlContainerChildPair(xmlNode, dataContainerNode);
262             return traverseXmlNodeContainingNotification(xmlContainerChildPair.getKey(),
263                     xmlContainerChildPair.getValue(), builder);
264         } else if (schemaNode instanceof ListSchemaNode) {
265             ListSchemaNode listSchemaNode = (ListSchemaNode) schemaNode;
266             builder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
267
268             Map<QName, Object> listKeys = findXmlListKeys(xmlNode, listSchemaNode);
269             builder.nodeWithKey(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()), listKeys);
270
271             Entry<Node, SchemaNode> xmlListChildPair = findXmlListChildPair(xmlNode, listSchemaNode);
272             return traverseXmlNodeContainingNotification(xmlListChildPair.getKey(),
273                     xmlListChildPair.getValue(), builder);
274         } else if (schemaNode instanceof NotificationDefinition) {
275             builder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
276
277             NotificationDefinition notificationDefinition = (NotificationDefinition) schemaNode;
278             return new NestedNotificationInfo(notificationDefinition,
279                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, builder.build()), xmlNode);
280         }
281         throw new IllegalStateException("No notification found");
282     }
283
284     private static Entry<Node, SchemaNode> findXmlContainerChildPair(final Node xmlNode,
285             final ContainerSchemaNode container) {
286         final NodeList nodeList = xmlNode.getChildNodes();
287         final Map<QName, SchemaNode> childrenWithoutRevision =
288                 Streams.concat(container.getChildNodes().stream(), container.getNotifications().stream())
289                     .collect(Collectors.toMap(child -> child.getQName().withoutRevision(), Function.identity()));
290
291         for (int i = 0; i < nodeList.getLength(); i++) {
292             Node currentNode = nodeList.item(i);
293             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
294                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
295                 SchemaNode schemaChildNode = childrenWithoutRevision.get(currentNodeQName);
296                 if (schemaChildNode != null) {
297                     return new AbstractMap.SimpleEntry<>(currentNode, schemaChildNode);
298                 }
299             }
300         }
301         throw new IllegalStateException("No container child found.");
302     }
303
304     private static Map<QName, Object> findXmlListKeys(final Node xmlNode, final ListSchemaNode listSchemaNode) {
305         Map<QName, Object> listKeys = new HashMap<>();
306         NodeList nodeList = xmlNode.getChildNodes();
307         Set<QName> keyDefinitionsWithoutRevision = listSchemaNode.getKeyDefinition().stream()
308                 .map(QName::withoutRevision).collect(Collectors.toSet());
309         for (int i = 0; i < nodeList.getLength(); i++) {
310             Node currentNode = nodeList.item(i);
311             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
312                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
313                 if (keyDefinitionsWithoutRevision.contains(currentNodeQName)) {
314                     listKeys.put(currentNodeQName, currentNode.getFirstChild().getNodeValue());
315                 }
316             }
317         }
318         if (listKeys.isEmpty()) {
319             throw new IllegalStateException("Notification cannot be contained in list without key statement.");
320         }
321         return listKeys;
322     }
323
324     private static Entry<Node, SchemaNode> findXmlListChildPair(final Node xmlNode, final ListSchemaNode list) {
325         final NodeList nodeList = xmlNode.getChildNodes();
326         for (int i = 0; i < nodeList.getLength(); i++) {
327             Node currentNode = nodeList.item(i);
328             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
329                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
330                 for (SchemaNode childNode : Iterables.concat(list.getChildNodes(), list.getNotifications())) {
331                     if (!list.getKeyDefinition().contains(childNode.getQName())
332                             && currentNodeQName.isEqualWithoutRevision(childNode.getQName())) {
333                         return new AbstractMap.SimpleEntry<>(currentNode, childNode);
334                     }
335                 }
336             }
337         }
338         throw new IllegalStateException("No list child found.");
339     }
340
341     private static NotificationDefinition getMostRecentNotification(
342             final Collection<? extends NotificationDefinition> notificationDefinitions) {
343         return Collections.max(notificationDefinitions, (o1, o2) ->
344             Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
345     }
346
347     @Override
348     public NetconfMessage toRpcRequest(final QName rpc, final NormalizedNode payload) {
349         // In case no input for rpc is defined, we can simply construct the payload here
350
351         // Determine whether a base netconf operation is being invoked
352         // and also check if the device exposed model for base netconf.
353         // If no, use pre built base netconf operations model
354         final boolean needToUseBaseCtx = mappedRpcs.get(rpc) == null && isBaseOrNotificationRpc(rpc);
355         final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
356         if (needToUseBaseCtx) {
357             currentMappedRpcs = baseSchema.getMappedRpcs();
358         } else {
359             currentMappedRpcs = mappedRpcs;
360         }
361
362         final RpcDefinition mappedRpc = Preconditions.checkNotNull(currentMappedRpcs.get(rpc),
363                 "Unknown rpc %s, available rpcs: %s", rpc, currentMappedRpcs.keySet());
364         if (mappedRpc.getInput().getChildNodes().isEmpty()) {
365             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpc, counter)
366                 .getNode().getOwnerDocument());
367         }
368
369         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpc);
370
371         Preconditions.checkArgument(payload instanceof ContainerNode,
372                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpc, payload);
373         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpc, counter);
374         try {
375             // If the schema context for netconf device does not contain model for base netconf operations,
376             // use default pre build context with just the base model
377             // This way operations like lock/unlock are supported even if the source for base model was not provided
378             final EffectiveModelContext ctx = needToUseBaseCtx ? baseSchema.getEffectiveModelContext()
379                     : mountContext.getEffectiveModelContext();
380             NetconfMessageTransformUtil.writeNormalizedOperationInput((ContainerNode) payload, result, Absolute.of(rpc),
381                 ctx);
382         } catch (final XMLStreamException | IOException | IllegalStateException e) {
383             throw new IllegalStateException("Unable to serialize input of " + rpc, e);
384         }
385
386         final Document node = result.getNode().getOwnerDocument();
387
388         return new NetconfMessage(node);
389     }
390
391     @Override
392     public NetconfMessage toActionRequest(final Absolute action, final DOMDataTreeIdentifier domDataTreeIdentifier,
393             final NormalizedNode payload) {
394         final ActionDefinition actionDef = actions.get(action);
395         Preconditions.checkArgument(actionDef != null, "Action does not exist: %s", action);
396
397         final InputSchemaNode inputDef = actionDef.getInput();
398         if (inputDef.getChildNodes().isEmpty()) {
399             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
400                 domDataTreeIdentifier, counter, actionDef.getQName()).getNode().getOwnerDocument());
401         }
402
403         Preconditions.checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
404         Preconditions.checkArgument(payload instanceof ContainerNode,
405                 "Transforming an action with input: %s, payload has to be a container, but was: %s", action, payload);
406
407         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
408             domDataTreeIdentifier, counter, actionDef.getQName());
409         try {
410             NetconfMessageTransformUtil.writeNormalizedOperationInput((ContainerNode) payload, result, action,
411                 mountContext.getEffectiveModelContext());
412         } catch (final XMLStreamException | IOException | IllegalStateException e) {
413             throw new IllegalStateException("Unable to serialize input of " + action, e);
414         }
415
416         return new NetconfMessage(result.getNode().getOwnerDocument());
417     }
418
419     private static boolean isBaseOrNotificationRpc(final QName rpc) {
420         return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
421     }
422
423     @Override
424     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final QName rpc) {
425         final NormalizedNode normalizedNode;
426         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpc)) {
427             normalizedNode = Builders.containerBuilder()
428                     .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_NODEID)
429                     .withChild(Builders.anyXmlBuilder()
430                         .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
431                         .withValue(new DOMSource(NetconfMessageTransformUtil.getDataSubtree(message.getDocument())))
432                         .build())
433                     .build();
434         } else {
435             // Determine whether a base netconf operation is being invoked
436             // and also check if the device exposed model for base netconf.
437             // If no, use pre built base netconf operations model
438             final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
439             if (mappedRpcs.get(rpc) == null && isBaseOrNotificationRpc(rpc)) {
440                 currentMappedRpcs = baseSchema.getMappedRpcs();
441             } else {
442                 currentMappedRpcs = mappedRpcs;
443             }
444
445             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpc);
446             Preconditions.checkArgument(rpcDefinition != null,
447                     "Unable to parse response of %s, the rpc is unknown", rpc);
448
449             // In case no input for rpc is defined, we can simply construct the payload here
450             final Absolute rpcPath = Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName());
451             normalizedNode = parseResult(message, rpcDefinition, rpcPath);
452         }
453         return new DefaultDOMRpcResult(normalizedNode);
454     }
455
456     @Override
457     public DOMActionResult toActionResult(final Absolute action, final NetconfMessage message) {
458         final ActionDefinition actionDefinition = actions.get(action);
459         Preconditions.checkArgument(actionDefinition != null, "Action does not exist: %s", action);
460
461         final SchemaInferenceStack stack = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), action);
462         stack.enterSchemaTree(actionDefinition.getOutput().getQName());
463         final Absolute actionPath = stack.toSchemaNodeIdentifier();
464
465         final ContainerNode normalizedNode = (ContainerNode) parseResult(message, actionDefinition, actionPath);
466         if (normalizedNode == null) {
467             return new SimpleDOMActionResult(Collections.emptyList());
468         } else {
469             return new SimpleDOMActionResult(normalizedNode, Collections.emptyList());
470         }
471     }
472
473     private NormalizedNode parseResult(final NetconfMessage message, final OperationDefinition operationDefinition,
474                                        final Absolute operationPath) {
475         final Optional<XmlElement> okResponseElement = XmlElement.fromDomDocument(message.getDocument())
476                 .getOnlyChildElementWithSameNamespaceOptionally("ok");
477         if (operationDefinition.getOutput().getChildNodes().isEmpty()) {
478             Preconditions.checkArgument(okResponseElement.isPresent(),
479                 "Unexpected content in response of rpc: %s, %s", operationDefinition.getQName(), message);
480             return null;
481         } else {
482             if (okResponseElement.isPresent()) {
483                 LOG.debug("Received response <ok/> for RPC with defined Output");
484                 return null;
485             }
486
487             final Element element = message.getDocument().getDocumentElement();
488             final Inference inference = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(),
489                     operationPath).toInference();
490             try {
491                 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
492                 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
493                 final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
494                         inference, strictParsing);
495                 xmlParser.traverse(new DOMSource(element));
496                 return resultHolder.getResult();
497             } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
498                 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
499             }
500         }
501     }
502
503     @Beta
504     public static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
505         private final ContainerNode content;
506         private final Absolute schemaPath;
507         private final Instant eventTime;
508
509         NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
510             this.content = content;
511             this.eventTime = eventTime;
512             this.schemaPath = Absolute.of(content.getIdentifier().getNodeType());
513         }
514
515         NetconfDeviceNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime) {
516             this.content = content;
517             this.eventTime = eventTime;
518             this.schemaPath = schemaPath;
519         }
520
521         @Override
522         public Absolute getType() {
523             return schemaPath;
524         }
525
526         @Override
527         public ContainerNode getBody() {
528             return content;
529         }
530
531         @Override
532         public Instant getEventInstant() {
533             return eventTime;
534         }
535     }
536
537     @Beta
538     public static class NetconfDeviceTreeNotification extends NetconfDeviceNotification {
539         private final DOMDataTreeIdentifier domDataTreeIdentifier;
540
541         NetconfDeviceTreeNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime,
542                 final DOMDataTreeIdentifier domDataTreeIdentifier) {
543             super(content, schemaPath, eventTime);
544             this.domDataTreeIdentifier = domDataTreeIdentifier;
545         }
546
547         public DOMDataTreeIdentifier getDomDataTreeIdentifier() {
548             return domDataTreeIdentifier;
549         }
550     }
551
552     private static final class NestedNotificationInfo {
553         private final NotificationDefinition notificationDefinition;
554         private final DOMDataTreeIdentifier domDataTreeIdentifier;
555         private final Node notificationNode;
556
557         NestedNotificationInfo(final NotificationDefinition notificationDefinition,
558                 final DOMDataTreeIdentifier domDataTreeIdentifier, final Node notificationNode) {
559             this.notificationDefinition = notificationDefinition;
560             this.domDataTreeIdentifier = domDataTreeIdentifier;
561             this.notificationNode = notificationNode;
562         }
563     }
564 }