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