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