Specialize MessageTransformer to NetconfMessage
[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 com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
16
17 import com.google.common.annotations.Beta;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Multimap;
25 import com.google.common.collect.Multimaps;
26 import com.google.common.collect.Streams;
27 import java.io.IOException;
28 import java.net.URISyntaxException;
29 import java.time.Instant;
30 import java.util.AbstractMap;
31 import java.util.ArrayDeque;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.Deque;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Optional;
42 import java.util.Set;
43 import java.util.function.Function;
44 import java.util.stream.Collectors;
45 import javax.xml.stream.XMLStreamException;
46 import javax.xml.transform.dom.DOMResult;
47 import javax.xml.transform.dom.DOMSource;
48 import org.checkerframework.checker.lock.qual.GuardedBy;
49 import org.eclipse.jdt.annotation.NonNull;
50 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
51 import org.opendaylight.mdsal.dom.api.DOMActionResult;
52 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
53 import org.opendaylight.mdsal.dom.api.DOMEvent;
54 import org.opendaylight.mdsal.dom.api.DOMNotification;
55 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
56 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
57 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
58 import org.opendaylight.netconf.api.NetconfMessage;
59 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
60 import org.opendaylight.netconf.api.xml.XmlElement;
61 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
62 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
63 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
64 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.Revision;
67 import org.opendaylight.yangtools.yang.common.XMLNamespace;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
73 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
74 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
75 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
76 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
77 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
78 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
79 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
86 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.Module;
89 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
90 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
94 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97 import org.w3c.dom.Document;
98 import org.w3c.dom.Element;
99 import org.w3c.dom.Node;
100 import org.w3c.dom.NodeList;
101 import org.xml.sax.SAXException;
102
103 public class NetconfMessageTransformer implements MessageTransformer {
104     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
105
106     private static final ImmutableSet<XMLNamespace> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
107         NETCONF_URI,
108         IETF_NETCONF_NOTIFICATIONS.getNamespace(),
109         CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
110
111     private final MountPointContext mountContext;
112     private final DataSchemaContextTree contextTree;
113     private final BaseSchema baseSchema;
114     private final MessageCounter counter;
115     private final ImmutableMap<QName, ? extends RpcDefinition> mappedRpcs;
116     private final Multimap<QName, ? extends NotificationDefinition> mappedNotifications;
117     private final boolean strictParsing;
118     private final ImmutableMap<Absolute, ActionDefinition> actions;
119
120     public NetconfMessageTransformer(final MountPointContext mountContext, final boolean strictParsing,
121                                      final BaseSchema baseSchema) {
122         counter = new MessageCounter();
123         this.mountContext = requireNonNull(mountContext);
124
125         final EffectiveModelContext schemaContext = mountContext.getEffectiveModelContext();
126         contextTree = DataSchemaContextTree.from(schemaContext);
127
128         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
129         actions = getActions(schemaContext);
130
131         // RFC6020 normal notifications
132         mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
133             node -> node.getQName().withoutRevision());
134         this.baseSchema = baseSchema;
135         this.strictParsing = strictParsing;
136     }
137
138     @VisibleForTesting
139     static ImmutableMap<Absolute, ActionDefinition> getActions(final EffectiveModelContext schemaContext) {
140         final var builder = ImmutableMap.<Absolute, ActionDefinition>builder();
141         findAction(schemaContext, new ArrayDeque<QName>(), builder);
142         return builder.build();
143     }
144
145     private static void findAction(final DataSchemaNode dataSchemaNode, final Deque<QName> path,
146             final ImmutableMap.Builder<Absolute, ActionDefinition> builder) {
147         if (dataSchemaNode instanceof ActionNodeContainer) {
148             for (ActionDefinition actionDefinition : ((ActionNodeContainer) dataSchemaNode).getActions()) {
149                 path.addLast(actionDefinition.getQName());
150                 builder.put(Absolute.of(path), actionDefinition);
151                 path.removeLast();
152             }
153         }
154         if (dataSchemaNode instanceof DataNodeContainer) {
155             for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
156                 path.addLast(innerDataSchemaNode.getQName());
157                 findAction(innerDataSchemaNode, path, builder);
158                 path.removeLast();
159             }
160         } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
161             for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases()) {
162                 path.addLast(caze.getQName());
163                 findAction(caze, path, builder);
164                 path.removeLast();
165             }
166         }
167     }
168
169     @Override
170     public synchronized DOMNotification toNotification(final NetconfMessage message) {
171         final Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
172         final QName notificationNoRev;
173         try {
174             notificationNoRev = QName.create(
175                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
176         } catch (final MissingNameSpaceException e) {
177             throw new IllegalArgumentException(
178                     "Unable to parse notification " + message + ", cannot find namespace", e);
179         }
180
181         final var matchingTopLevel = mappedNotifications.get(notificationNoRev);
182         final var element = stripped.getValue().getDomElement();
183         if (!matchingTopLevel.isEmpty()) {
184             final var notification = getMostRecentNotification(matchingTopLevel);
185             // FIXME: we really should have a pre-constructed identifier here
186             return new NetconfDeviceNotification(toNotification(Absolute.of(notification.getQName()), element),
187                 stripped.getKey());
188         }
189
190         final var nestedInfo = findNestedNotification(message, element)
191             .orElseThrow(() -> new IllegalArgumentException("Unable to parse notification for " + element
192                 + ". Available notifications: " + mappedNotifications.keySet()));
193         final var schemaPath = nestedInfo.schemaPath;
194         return new NetconfDeviceTreeNotification(toNotification(schemaPath, nestedInfo.element), schemaPath,
195             stripped.getKey(), nestedInfo.instancePath);
196     }
197
198     @GuardedBy("this")
199     private ContainerNode toNotification(final Absolute notificationPath, final Element element) {
200         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
201         try {
202             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
203             final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
204                     SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), notificationPath).toInference(),
205                     strictParsing);
206             xmlParser.traverse(new DOMSource(element));
207         } catch (XMLStreamException | URISyntaxException | IOException | SAXException
208                 | UnsupportedOperationException e) {
209             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
210         }
211         return (ContainerNode) resultHolder.getResult();
212     }
213
214     private Optional<NestedNotificationInfo> findNestedNotification(final NetconfMessage message,
215             final Element element) {
216         final Iterator<? extends Module> modules = mountContext.getEffectiveModelContext()
217                 .findModules(XMLNamespace.of(element.getNamespaceURI())).iterator();
218         if (!modules.hasNext()) {
219             throw new IllegalArgumentException(
220                     "Unable to parse notification " + message + ", cannot find top level module");
221         }
222         final Module module = modules.next();
223         final QName topLevelNodeQName = QName.create(element.getNamespaceURI(), element.getLocalName());
224         for (DataSchemaNode childNode : module.getChildNodes()) {
225             if (topLevelNodeQName.isEqualWithoutRevision(childNode.getQName())) {
226                 return Optional.of(traverseXmlNodeContainingNotification(element, childNode, new ArrayList<>(),
227                     YangInstanceIdentifier.builder()));
228             }
229         }
230         return Optional.empty();
231     }
232
233     // FIXME: this method is using QNames which are not bound to a Revision. Why is that?
234     // FIXME: furthermore this does not handle the entirety of schema layout: notably missing a choice/case schema nodes
235     private NestedNotificationInfo traverseXmlNodeContainingNotification(final Node xmlNode,
236             final SchemaNode schemaNode, final List<QName> schemaBuilder,
237             final InstanceIdentifierBuilder instanceBuilder) {
238         if (schemaNode instanceof ContainerSchemaNode containerSchema) {
239             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
240             schemaBuilder.add(containerSchema.getQName());
241
242             Entry<Node, SchemaNode> xmlContainerChildPair = findXmlContainerChildPair(xmlNode, containerSchema);
243             return traverseXmlNodeContainingNotification(xmlContainerChildPair.getKey(),
244                     xmlContainerChildPair.getValue(), schemaBuilder, instanceBuilder);
245         } else if (schemaNode instanceof ListSchemaNode listSchema) {
246             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
247             schemaBuilder.add(listSchema.getQName());
248
249             Map<QName, Object> listKeys = findXmlListKeys(xmlNode, listSchema);
250             instanceBuilder.nodeWithKey(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()), listKeys);
251
252             Entry<Node, SchemaNode> xmlListChildPair = findXmlListChildPair(xmlNode, listSchema);
253             return traverseXmlNodeContainingNotification(xmlListChildPair.getKey(),
254                     xmlListChildPair.getValue(), schemaBuilder, instanceBuilder);
255         } else if (schemaNode instanceof NotificationDefinition) {
256             // FIXME: this should not be here: it does not form a valid YangInstanceIdentifier
257             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
258             schemaBuilder.add(schemaNode.getQName());
259
260             return new NestedNotificationInfo(Absolute.of(schemaBuilder),
261                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceBuilder.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 Map.entry(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 = 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         checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpc);
352
353         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         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         checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
386         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             checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpc);
429
430             // In case no input for rpc is defined, we can simply construct the payload here
431             normalizedNode = parseResult(message, Absolute.of(rpc), rpcDefinition);
432         }
433         return new DefaultDOMRpcResult(normalizedNode);
434     }
435
436     @Override
437     public DOMActionResult toActionResult(final Absolute action, final NetconfMessage message) {
438         final ActionDefinition actionDefinition = actions.get(action);
439         checkArgument(actionDefinition != null, "Action does not exist: %s", action);
440         final ContainerNode normalizedNode = (ContainerNode) parseResult(message, action, actionDefinition);
441
442         if (normalizedNode == null) {
443             return new SimpleDOMActionResult(List.of());
444         } else {
445             return new SimpleDOMActionResult(normalizedNode, List.of());
446         }
447     }
448
449     private NormalizedNode parseResult(final NetconfMessage message, final Absolute operationPath,
450             final OperationDefinition operationDef) {
451         final Optional<XmlElement> okResponseElement = XmlElement.fromDomDocument(message.getDocument())
452                 .getOnlyChildElementWithSameNamespaceOptionally("ok");
453         final var operOutput = operationDef.getOutput();
454         if (operOutput.getChildNodes().isEmpty()) {
455             checkArgument(okResponseElement.isPresent(), "Unexpected content in response of operation: %s, %s",
456                 operationDef.getQName(), message);
457             return null;
458         }
459         if (okResponseElement.isPresent()) {
460             // FIXME: could be an action as well
461             LOG.debug("Received response <ok/> for RPC with defined Output");
462             return null;
463         }
464
465         final var operSteps = operationPath.getNodeIdentifiers();
466         final var outputPath = Absolute.of(ImmutableList.<QName>builderWithExpectedSize(operSteps.size() + 1)
467             .addAll(operSteps)
468             .add(operOutput.getQName())
469             .build());
470         // FIXME: we should have a cached inference here, or XMLParserStream should accept Absolute instead
471         final var inference = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), outputPath)
472             .toInference();
473
474         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
475         final Element element = message.getDocument().getDocumentElement();
476         try {
477             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
478             final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext, inference, strictParsing);
479             xmlParser.traverse(new DOMSource(element));
480         } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
481             throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
482         }
483         return resultHolder.getResult();
484     }
485
486     @Beta
487     public static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
488         private final ContainerNode content;
489         private final Absolute schemaPath;
490         private final Instant eventTime;
491
492         NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
493             this.content = content;
494             this.eventTime = eventTime;
495             schemaPath = Absolute.of(content.getIdentifier().getNodeType());
496         }
497
498         NetconfDeviceNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime) {
499             this.content = content;
500             this.eventTime = eventTime;
501             this.schemaPath = schemaPath;
502         }
503
504         @Override
505         public Absolute getType() {
506             return schemaPath;
507         }
508
509         @Override
510         public ContainerNode getBody() {
511             return content;
512         }
513
514         @Override
515         public Instant getEventInstant() {
516             return eventTime;
517         }
518     }
519
520     @Beta
521     public static class NetconfDeviceTreeNotification extends NetconfDeviceNotification {
522         private final DOMDataTreeIdentifier domDataTreeIdentifier;
523
524         NetconfDeviceTreeNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime,
525                 final DOMDataTreeIdentifier domDataTreeIdentifier) {
526             super(content, schemaPath, eventTime);
527             this.domDataTreeIdentifier = domDataTreeIdentifier;
528         }
529
530         public DOMDataTreeIdentifier getDomDataTreeIdentifier() {
531             return domDataTreeIdentifier;
532         }
533     }
534
535     private static final class NestedNotificationInfo {
536         final @NonNull DOMDataTreeIdentifier instancePath;
537         final @NonNull Absolute schemaPath;
538         final @NonNull Element element;
539
540         NestedNotificationInfo(final Absolute schemaPath, final DOMDataTreeIdentifier instancePath,
541                 final Node documentNode) {
542             this.schemaPath = requireNonNull(schemaPath);
543             this.instancePath = requireNonNull(instancePath);
544             checkArgument(documentNode instanceof Element, "Unexpected document node %s", documentNode);
545             element = (Element) documentNode;
546         }
547     }
548 }