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