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