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 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
14 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
15 import static org.opendaylight.netconf.client.mdsal.impl.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.time.Instant;
29 import java.util.AbstractMap;
30 import java.util.ArrayDeque;
31 import java.util.ArrayList;
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.eclipse.jdt.annotation.NonNull;
49 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
50 import org.opendaylight.mdsal.dom.api.DOMActionResult;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
52 import org.opendaylight.mdsal.dom.api.DOMEvent;
53 import org.opendaylight.mdsal.dom.api.DOMNotification;
54 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
55 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
56 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
57 import org.opendaylight.netconf.api.messages.NetconfMessage;
58 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
59 import org.opendaylight.netconf.api.xml.XmlElement;
60 import org.opendaylight.netconf.client.mdsal.api.ActionTransformer;
61 import org.opendaylight.netconf.client.mdsal.api.NotificationTransformer;
62 import org.opendaylight.netconf.client.mdsal.api.RpcTransformer;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.common.Revision;
65 import org.opendaylight.yangtools.yang.common.RpcResult;
66 import org.opendaylight.yangtools.yang.common.XMLNamespace;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
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.NormalizationResultHolder;
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
102 public class NetconfMessageTransformer
103         implements ActionTransformer, NotificationTransformer, RpcTransformer<ContainerNode, DOMRpcResult> {
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<>(), 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 NormalizationResultHolder resultHolder = new NormalizationResultHolder();
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 | IOException | UnsupportedOperationException e) {
208             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
209         }
210         return (ContainerNode) resultHolder.getResult().data();
211     }
212
213     private Optional<NestedNotificationInfo> findNestedNotification(final NetconfMessage message,
214             final Element element) {
215         final Iterator<? extends Module> modules = mountContext.getEffectiveModelContext()
216                 .findModules(XMLNamespace.of(element.getNamespaceURI())).iterator();
217         if (!modules.hasNext()) {
218             throw new IllegalArgumentException(
219                     "Unable to parse notification " + message + ", cannot find top level module");
220         }
221         final Module module = modules.next();
222         final QName topLevelNodeQName = QName.create(element.getNamespaceURI(), element.getLocalName());
223         for (DataSchemaNode childNode : module.getChildNodes()) {
224             if (topLevelNodeQName.isEqualWithoutRevision(childNode.getQName())) {
225                 return Optional.of(traverseXmlNodeContainingNotification(element, childNode, new ArrayList<>(),
226                     YangInstanceIdentifier.builder()));
227             }
228         }
229         return Optional.empty();
230     }
231
232     // FIXME: this method is using QNames which are not bound to a Revision. Why is that?
233     // FIXME: furthermore this does not handle the entirety of schema layout: notably missing a choice/case schema nodes
234     private NestedNotificationInfo traverseXmlNodeContainingNotification(final Node xmlNode,
235             final SchemaNode schemaNode, final List<QName> schemaBuilder,
236             final InstanceIdentifierBuilder instanceBuilder) {
237         if (schemaNode instanceof ContainerSchemaNode containerSchema) {
238             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
239             schemaBuilder.add(containerSchema.getQName());
240
241             Entry<Node, SchemaNode> xmlContainerChildPair = findXmlContainerChildPair(xmlNode, containerSchema);
242             return traverseXmlNodeContainingNotification(xmlContainerChildPair.getKey(),
243                     xmlContainerChildPair.getValue(), schemaBuilder, instanceBuilder);
244         } else if (schemaNode instanceof ListSchemaNode listSchema) {
245             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
246             schemaBuilder.add(listSchema.getQName());
247
248             Map<QName, Object> listKeys = findXmlListKeys(xmlNode, listSchema);
249             instanceBuilder.nodeWithKey(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()), listKeys);
250
251             Entry<Node, SchemaNode> xmlListChildPair = findXmlListChildPair(xmlNode, listSchema);
252             return traverseXmlNodeContainingNotification(xmlListChildPair.getKey(),
253                     xmlListChildPair.getValue(), schemaBuilder, instanceBuilder);
254         } else if (schemaNode instanceof NotificationDefinition) {
255             // FIXME: this should not be here: it does not form a valid YangInstanceIdentifier
256             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
257             schemaBuilder.add(schemaNode.getQName());
258
259             return new NestedNotificationInfo(Absolute.of(schemaBuilder),
260                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceBuilder.build()), xmlNode);
261         }
262         throw new IllegalStateException("No notification found");
263     }
264
265     private static Entry<Node, SchemaNode> findXmlContainerChildPair(final Node xmlNode,
266             final ContainerSchemaNode container) {
267         final NodeList nodeList = xmlNode.getChildNodes();
268         final Map<QName, SchemaNode> childrenWithoutRevision =
269                 Streams.concat(container.getChildNodes().stream(), container.getNotifications().stream())
270                     .collect(Collectors.toMap(child -> child.getQName().withoutRevision(), Function.identity()));
271
272         for (int i = 0; i < nodeList.getLength(); i++) {
273             Node currentNode = nodeList.item(i);
274             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
275                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
276                 SchemaNode schemaChildNode = childrenWithoutRevision.get(currentNodeQName);
277                 if (schemaChildNode != null) {
278                     return Map.entry(currentNode, schemaChildNode);
279                 }
280             }
281         }
282         throw new IllegalStateException("No container child found.");
283     }
284
285     private static Map<QName, Object> findXmlListKeys(final Node xmlNode, final ListSchemaNode listSchemaNode) {
286         Map<QName, Object> listKeys = new HashMap<>();
287         NodeList nodeList = xmlNode.getChildNodes();
288         Set<QName> keyDefinitionsWithoutRevision = listSchemaNode.getKeyDefinition().stream()
289                 .map(QName::withoutRevision).collect(Collectors.toSet());
290         for (int i = 0; i < nodeList.getLength(); i++) {
291             Node currentNode = nodeList.item(i);
292             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
293                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
294                 if (keyDefinitionsWithoutRevision.contains(currentNodeQName)) {
295                     listKeys.put(currentNodeQName, currentNode.getFirstChild().getNodeValue());
296                 }
297             }
298         }
299         if (listKeys.isEmpty()) {
300             throw new IllegalStateException("Notification cannot be contained in list without key statement.");
301         }
302         return listKeys;
303     }
304
305     private static Entry<Node, SchemaNode> findXmlListChildPair(final Node xmlNode, final ListSchemaNode list) {
306         final NodeList nodeList = xmlNode.getChildNodes();
307         for (int i = 0; i < nodeList.getLength(); i++) {
308             Node currentNode = nodeList.item(i);
309             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
310                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
311                 for (SchemaNode childNode : Iterables.concat(list.getChildNodes(), list.getNotifications())) {
312                     if (!list.getKeyDefinition().contains(childNode.getQName())
313                             && currentNodeQName.isEqualWithoutRevision(childNode.getQName())) {
314                         return new AbstractMap.SimpleEntry<>(currentNode, childNode);
315                     }
316                 }
317             }
318         }
319         throw new IllegalStateException("No list child found.");
320     }
321
322     private static NotificationDefinition getMostRecentNotification(
323             final Collection<? extends NotificationDefinition> notificationDefinitions) {
324         return Collections.max(notificationDefinitions, (o1, o2) ->
325             Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
326     }
327
328     @Override
329     public NetconfMessage toRpcRequest(final QName rpc, final ContainerNode payload) {
330         // In case no input for rpc is defined, we can simply construct the payload here
331
332         // Determine whether a base netconf operation is being invoked
333         // and also check if the device exposed model for base netconf.
334         // If no, use pre built base netconf operations model
335         final boolean needToUseBaseCtx = mappedRpcs.get(rpc) == null && isBaseOrNotificationRpc(rpc);
336         final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
337         if (needToUseBaseCtx) {
338             currentMappedRpcs = baseSchema.getMappedRpcs();
339         } else {
340             currentMappedRpcs = mappedRpcs;
341         }
342
343         final RpcDefinition mappedRpc = checkNotNull(currentMappedRpcs.get(rpc),
344                 "Unknown rpc %s, available rpcs: %s", rpc, currentMappedRpcs.keySet());
345         if (mappedRpc.getInput().getChildNodes().isEmpty()) {
346             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpc, counter)
347                 .getNode().getOwnerDocument());
348         }
349
350         checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpc);
351
352         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpc, counter);
353         try {
354             // If the schema context for netconf device does not contain model for base netconf operations,
355             // use default pre build context with just the base model
356             // This way operations like lock/unlock are supported even if the source for base model was not provided
357             final EffectiveModelContext ctx = needToUseBaseCtx ? baseSchema.getEffectiveModelContext()
358                     : mountContext.getEffectiveModelContext();
359             NetconfMessageTransformUtil.writeNormalizedOperationInput(payload, result, Absolute.of(rpc),
360                 ctx);
361         } catch (final XMLStreamException | IOException | IllegalStateException e) {
362             throw new IllegalStateException("Unable to serialize input of " + rpc, e);
363         }
364
365         final Document node = result.getNode().getOwnerDocument();
366
367         return new NetconfMessage(node);
368     }
369
370     @Override
371     public NetconfMessage toActionRequest(final Absolute action, final DOMDataTreeIdentifier domDataTreeIdentifier,
372             final NormalizedNode payload) {
373         final ActionDefinition actionDef = actions.get(action);
374         checkArgument(actionDef != null, "Action does not exist: %s", action);
375
376         final InputSchemaNode inputDef = actionDef.getInput();
377         if (inputDef.getChildNodes().isEmpty()) {
378             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
379                 domDataTreeIdentifier, counter, actionDef.getQName()).getNode().getOwnerDocument());
380         }
381
382         checkNotNull(payload, "Transforming an action with input: %s, payload cannot be null", action);
383         checkArgument(payload instanceof ContainerNode,
384                 "Transforming an action with input: %s, payload has to be a container, but was: %s", action, payload);
385
386         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForActionRequest(contextTree,
387             domDataTreeIdentifier, counter, actionDef.getQName());
388         try {
389             NetconfMessageTransformUtil.writeNormalizedOperationInput((ContainerNode) payload, result, action,
390                 mountContext.getEffectiveModelContext());
391         } catch (final XMLStreamException | IOException | IllegalStateException e) {
392             throw new IllegalStateException("Unable to serialize input of " + action, e);
393         }
394
395         return new NetconfMessage(result.getNode().getOwnerDocument());
396     }
397
398     private static boolean isBaseOrNotificationRpc(final QName rpc) {
399         return BASE_OR_NOTIFICATION_NS.contains(rpc.getNamespace());
400     }
401
402     @Override
403     public synchronized DOMRpcResult toRpcResult(final RpcResult<NetconfMessage> resultPayload, final QName rpc) {
404         if (!resultPayload.isSuccessful()) {
405             return new DefaultDOMRpcResult(resultPayload.getErrors());
406         }
407
408         final var message = resultPayload.getResult();
409         final ContainerNode normalizedNode;
410         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpc)) {
411             normalizedNode = Builders.containerBuilder()
412                     .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_NODEID)
413                     .withChild(Builders.anyXmlBuilder()
414                         .withNodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_NODEID)
415                         .withValue(new DOMSource(NetconfMessageTransformUtil.getDataSubtree(message.getDocument())))
416                         .build())
417                     .build();
418         } else {
419             // Determine whether a base netconf operation is being invoked
420             // and also check if the device exposed model for base netconf.
421             // If no, use pre built base netconf operations model
422             final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
423             if (mappedRpcs.get(rpc) == null && isBaseOrNotificationRpc(rpc)) {
424                 currentMappedRpcs = baseSchema.getMappedRpcs();
425             } else {
426                 currentMappedRpcs = mappedRpcs;
427             }
428
429             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpc);
430             checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpc);
431
432             // In case no input for rpc is defined, we can simply construct the payload here
433             normalizedNode = parseResult(message, Absolute.of(rpc), rpcDefinition);
434         }
435         return new DefaultDOMRpcResult(normalizedNode);
436     }
437
438     @Override
439     public DOMActionResult toActionResult(final Absolute action, final NetconfMessage message) {
440         final ActionDefinition actionDefinition = actions.get(action);
441         checkArgument(actionDefinition != null, "Action does not exist: %s", action);
442         final ContainerNode normalizedNode = parseResult(message, action, actionDefinition);
443
444         if (normalizedNode == null) {
445             return new SimpleDOMActionResult(List.of());
446         } else {
447             return new SimpleDOMActionResult(normalizedNode, List.of());
448         }
449     }
450
451     private ContainerNode parseResult(final NetconfMessage message, final Absolute operationPath,
452             final OperationDefinition operationDef) {
453         final Optional<XmlElement> okResponseElement = XmlElement.fromDomDocument(message.getDocument())
454                 .getOnlyChildElementWithSameNamespaceOptionally("ok");
455         final var operOutput = operationDef.getOutput();
456         if (operOutput.getChildNodes().isEmpty()) {
457             checkArgument(okResponseElement.isPresent(), "Unexpected content in response of operation: %s, %s",
458                 operationDef.getQName(), message);
459             return null;
460         }
461         if (okResponseElement.isPresent()) {
462             // FIXME: could be an action as well
463             LOG.debug("Received response <ok/> for RPC with defined Output");
464             return null;
465         }
466
467         final var operSteps = operationPath.getNodeIdentifiers();
468         final var outputPath = Absolute.of(ImmutableList.<QName>builderWithExpectedSize(operSteps.size() + 1)
469             .addAll(operSteps)
470             .add(operOutput.getQName())
471             .build());
472         // FIXME: we should have a cached inference here, or XMLParserStream should accept Absolute instead
473         final var inference = SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), outputPath)
474             .toInference();
475
476         final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
477         final Element element = message.getDocument().getDocumentElement();
478         try {
479             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
480             final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext, inference, strictParsing);
481             xmlParser.traverse(new DOMSource(element));
482         } catch (XMLStreamException | IOException e) {
483             throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
484         }
485         return (ContainerNode) resultHolder.getResult().data();
486     }
487
488     @Beta
489     public static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
490         private final ContainerNode content;
491         private final Absolute schemaPath;
492         private final Instant eventTime;
493
494         NetconfDeviceNotification(final ContainerNode content, final Instant eventTime) {
495             this.content = content;
496             this.eventTime = eventTime;
497             schemaPath = Absolute.of(content.name().getNodeType());
498         }
499
500         NetconfDeviceNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime) {
501             this.content = content;
502             this.eventTime = eventTime;
503             this.schemaPath = schemaPath;
504         }
505
506         @Override
507         public Absolute getType() {
508             return schemaPath;
509         }
510
511         @Override
512         public ContainerNode getBody() {
513             return content;
514         }
515
516         @Override
517         public Instant getEventInstant() {
518             return eventTime;
519         }
520     }
521
522     @Beta
523     public static class NetconfDeviceTreeNotification extends NetconfDeviceNotification {
524         private final DOMDataTreeIdentifier domDataTreeIdentifier;
525
526         NetconfDeviceTreeNotification(final ContainerNode content, final Absolute schemaPath, final Instant eventTime,
527                 final DOMDataTreeIdentifier domDataTreeIdentifier) {
528             super(content, schemaPath, eventTime);
529             this.domDataTreeIdentifier = domDataTreeIdentifier;
530         }
531
532         public DOMDataTreeIdentifier getDomDataTreeIdentifier() {
533             return domDataTreeIdentifier;
534         }
535     }
536
537     private static final class NestedNotificationInfo {
538         final @NonNull DOMDataTreeIdentifier instancePath;
539         final @NonNull Absolute schemaPath;
540         final @NonNull Element element;
541
542         NestedNotificationInfo(final Absolute schemaPath, final DOMDataTreeIdentifier instancePath,
543                 final Node documentNode) {
544             this.schemaPath = requireNonNull(schemaPath);
545             this.instancePath = requireNonNull(instancePath);
546             checkArgument(documentNode instanceof Element, "Unexpected document node %s", documentNode);
547             element = (Element) documentNode;
548         }
549     }
550 }