Split up MessageTransformer
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / schema / mapping / NetconfMessageTransformer.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.sal.connect.netconf.schema.mapping;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
15 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
16
17 import com.google.common.annotations.Beta;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Multimap;
25 import com.google.common.collect.Multimaps;
26 import com.google.common.collect.Streams;
27 import java.io.IOException;
28 import java.net.URISyntaxException;
29 import java.time.Instant;
30 import java.util.AbstractMap;
31 import java.util.ArrayDeque;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.Deque;
36 import java.util.HashMap;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Map.Entry;
41 import java.util.Optional;
42 import java.util.Set;
43 import java.util.function.Function;
44 import java.util.stream.Collectors;
45 import javax.xml.stream.XMLStreamException;
46 import javax.xml.transform.dom.DOMResult;
47 import javax.xml.transform.dom.DOMSource;
48 import org.checkerframework.checker.lock.qual.GuardedBy;
49 import org.eclipse.jdt.annotation.NonNull;
50 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
51 import org.opendaylight.mdsal.dom.api.DOMActionResult;
52 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
53 import org.opendaylight.mdsal.dom.api.DOMEvent;
54 import org.opendaylight.mdsal.dom.api.DOMNotification;
55 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
56 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
57 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
58 import org.opendaylight.netconf.api.NetconfMessage;
59 import org.opendaylight.netconf.api.xml.MissingNameSpaceException;
60 import org.opendaylight.netconf.api.xml.XmlElement;
61 import org.opendaylight.netconf.sal.connect.api.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.XMLNamespace;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
72 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
75 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
76 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
77 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
78 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
79 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
80 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
81 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
82 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
88 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
92 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
93 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
96 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99 import org.w3c.dom.Document;
100 import org.w3c.dom.Element;
101 import org.w3c.dom.Node;
102 import org.w3c.dom.NodeList;
103 import org.xml.sax.SAXException;
104
105 public class NetconfMessageTransformer implements ActionTransformer, NotificationTransformer, RpcTransformer {
106     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
107
108     private static final ImmutableSet<XMLNamespace> BASE_OR_NOTIFICATION_NS = ImmutableSet.of(
109         NETCONF_URI,
110         IETF_NETCONF_NOTIFICATIONS.getNamespace(),
111         CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
112
113     private final MountPointContext mountContext;
114     private final DataSchemaContextTree contextTree;
115     private final BaseSchema baseSchema;
116     private final MessageCounter counter;
117     private final ImmutableMap<QName, ? extends RpcDefinition> mappedRpcs;
118     private final Multimap<QName, ? extends NotificationDefinition> mappedNotifications;
119     private final boolean strictParsing;
120     private final ImmutableMap<Absolute, ActionDefinition> actions;
121
122     public NetconfMessageTransformer(final MountPointContext mountContext, final boolean strictParsing,
123                                      final BaseSchema baseSchema) {
124         counter = new MessageCounter();
125         this.mountContext = requireNonNull(mountContext);
126
127         final EffectiveModelContext schemaContext = mountContext.getEffectiveModelContext();
128         contextTree = DataSchemaContextTree.from(schemaContext);
129
130         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
131         actions = getActions(schemaContext);
132
133         // RFC6020 normal notifications
134         mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
135             node -> node.getQName().withoutRevision());
136         this.baseSchema = baseSchema;
137         this.strictParsing = strictParsing;
138     }
139
140     @VisibleForTesting
141     static ImmutableMap<Absolute, ActionDefinition> getActions(final EffectiveModelContext schemaContext) {
142         final var builder = ImmutableMap.<Absolute, ActionDefinition>builder();
143         findAction(schemaContext, new ArrayDeque<QName>(), builder);
144         return builder.build();
145     }
146
147     private static void findAction(final DataSchemaNode dataSchemaNode, final Deque<QName> path,
148             final ImmutableMap.Builder<Absolute, ActionDefinition> builder) {
149         if (dataSchemaNode instanceof ActionNodeContainer) {
150             for (ActionDefinition actionDefinition : ((ActionNodeContainer) dataSchemaNode).getActions()) {
151                 path.addLast(actionDefinition.getQName());
152                 builder.put(Absolute.of(path), actionDefinition);
153                 path.removeLast();
154             }
155         }
156         if (dataSchemaNode instanceof DataNodeContainer) {
157             for (DataSchemaNode innerDataSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
158                 path.addLast(innerDataSchemaNode.getQName());
159                 findAction(innerDataSchemaNode, path, builder);
160                 path.removeLast();
161             }
162         } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
163             for (CaseSchemaNode caze : ((ChoiceSchemaNode) dataSchemaNode).getCases()) {
164                 path.addLast(caze.getQName());
165                 findAction(caze, path, builder);
166                 path.removeLast();
167             }
168         }
169     }
170
171     @Override
172     public synchronized DOMNotification toNotification(final NetconfMessage message) {
173         final Entry<Instant, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
174         final QName notificationNoRev;
175         try {
176             notificationNoRev = QName.create(
177                     stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
178         } catch (final MissingNameSpaceException e) {
179             throw new IllegalArgumentException(
180                     "Unable to parse notification " + message + ", cannot find namespace", e);
181         }
182
183         final var matchingTopLevel = mappedNotifications.get(notificationNoRev);
184         final var element = stripped.getValue().getDomElement();
185         if (!matchingTopLevel.isEmpty()) {
186             final var notification = getMostRecentNotification(matchingTopLevel);
187             // FIXME: we really should have a pre-constructed identifier here
188             return new NetconfDeviceNotification(toNotification(Absolute.of(notification.getQName()), element),
189                 stripped.getKey());
190         }
191
192         final var nestedInfo = findNestedNotification(message, element)
193             .orElseThrow(() -> new IllegalArgumentException("Unable to parse notification for " + element
194                 + ". Available notifications: " + mappedNotifications.keySet()));
195         final var schemaPath = nestedInfo.schemaPath;
196         return new NetconfDeviceTreeNotification(toNotification(schemaPath, nestedInfo.element), schemaPath,
197             stripped.getKey(), nestedInfo.instancePath);
198     }
199
200     @GuardedBy("this")
201     private ContainerNode toNotification(final Absolute notificationPath, final Element element) {
202         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
203         try {
204             final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
205             final XmlParserStream xmlParser = XmlParserStream.create(writer, mountContext,
206                     SchemaInferenceStack.of(mountContext.getEffectiveModelContext(), notificationPath).toInference(),
207                     strictParsing);
208             xmlParser.traverse(new DOMSource(element));
209         } catch (XMLStreamException | URISyntaxException | IOException | SAXException
210                 | UnsupportedOperationException e) {
211             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
212         }
213         return (ContainerNode) resultHolder.getResult();
214     }
215
216     private Optional<NestedNotificationInfo> findNestedNotification(final NetconfMessage message,
217             final Element element) {
218         final Iterator<? extends Module> modules = mountContext.getEffectiveModelContext()
219                 .findModules(XMLNamespace.of(element.getNamespaceURI())).iterator();
220         if (!modules.hasNext()) {
221             throw new IllegalArgumentException(
222                     "Unable to parse notification " + message + ", cannot find top level module");
223         }
224         final Module module = modules.next();
225         final QName topLevelNodeQName = QName.create(element.getNamespaceURI(), element.getLocalName());
226         for (DataSchemaNode childNode : module.getChildNodes()) {
227             if (topLevelNodeQName.isEqualWithoutRevision(childNode.getQName())) {
228                 return Optional.of(traverseXmlNodeContainingNotification(element, childNode, new ArrayList<>(),
229                     YangInstanceIdentifier.builder()));
230             }
231         }
232         return Optional.empty();
233     }
234
235     // FIXME: this method is using QNames which are not bound to a Revision. Why is that?
236     // FIXME: furthermore this does not handle the entirety of schema layout: notably missing a choice/case schema nodes
237     private NestedNotificationInfo traverseXmlNodeContainingNotification(final Node xmlNode,
238             final SchemaNode schemaNode, final List<QName> schemaBuilder,
239             final InstanceIdentifierBuilder instanceBuilder) {
240         if (schemaNode instanceof ContainerSchemaNode containerSchema) {
241             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
242             schemaBuilder.add(containerSchema.getQName());
243
244             Entry<Node, SchemaNode> xmlContainerChildPair = findXmlContainerChildPair(xmlNode, containerSchema);
245             return traverseXmlNodeContainingNotification(xmlContainerChildPair.getKey(),
246                     xmlContainerChildPair.getValue(), schemaBuilder, instanceBuilder);
247         } else if (schemaNode instanceof ListSchemaNode listSchema) {
248             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
249             schemaBuilder.add(listSchema.getQName());
250
251             Map<QName, Object> listKeys = findXmlListKeys(xmlNode, listSchema);
252             instanceBuilder.nodeWithKey(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()), listKeys);
253
254             Entry<Node, SchemaNode> xmlListChildPair = findXmlListChildPair(xmlNode, listSchema);
255             return traverseXmlNodeContainingNotification(xmlListChildPair.getKey(),
256                     xmlListChildPair.getValue(), schemaBuilder, instanceBuilder);
257         } else if (schemaNode instanceof NotificationDefinition) {
258             // FIXME: this should not be here: it does not form a valid YangInstanceIdentifier
259             instanceBuilder.node(QName.create(xmlNode.getNamespaceURI(), xmlNode.getLocalName()));
260             schemaBuilder.add(schemaNode.getQName());
261
262             return new NestedNotificationInfo(Absolute.of(schemaBuilder),
263                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceBuilder.build()), xmlNode);
264         }
265         throw new IllegalStateException("No notification found");
266     }
267
268     private static Entry<Node, SchemaNode> findXmlContainerChildPair(final Node xmlNode,
269             final ContainerSchemaNode container) {
270         final NodeList nodeList = xmlNode.getChildNodes();
271         final Map<QName, SchemaNode> childrenWithoutRevision =
272                 Streams.concat(container.getChildNodes().stream(), container.getNotifications().stream())
273                     .collect(Collectors.toMap(child -> child.getQName().withoutRevision(), Function.identity()));
274
275         for (int i = 0; i < nodeList.getLength(); i++) {
276             Node currentNode = nodeList.item(i);
277             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
278                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
279                 SchemaNode schemaChildNode = childrenWithoutRevision.get(currentNodeQName);
280                 if (schemaChildNode != null) {
281                     return Map.entry(currentNode, schemaChildNode);
282                 }
283             }
284         }
285         throw new IllegalStateException("No container child found.");
286     }
287
288     private static Map<QName, Object> findXmlListKeys(final Node xmlNode, final ListSchemaNode listSchemaNode) {
289         Map<QName, Object> listKeys = new HashMap<>();
290         NodeList nodeList = xmlNode.getChildNodes();
291         Set<QName> keyDefinitionsWithoutRevision = listSchemaNode.getKeyDefinition().stream()
292                 .map(QName::withoutRevision).collect(Collectors.toSet());
293         for (int i = 0; i < nodeList.getLength(); i++) {
294             Node currentNode = nodeList.item(i);
295             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
296                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
297                 if (keyDefinitionsWithoutRevision.contains(currentNodeQName)) {
298                     listKeys.put(currentNodeQName, currentNode.getFirstChild().getNodeValue());
299                 }
300             }
301         }
302         if (listKeys.isEmpty()) {
303             throw new IllegalStateException("Notification cannot be contained in list without key statement.");
304         }
305         return listKeys;
306     }
307
308     private static Entry<Node, SchemaNode> findXmlListChildPair(final Node xmlNode, final ListSchemaNode list) {
309         final NodeList nodeList = xmlNode.getChildNodes();
310         for (int i = 0; i < nodeList.getLength(); i++) {
311             Node currentNode = nodeList.item(i);
312             if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
313                 QName currentNodeQName = QName.create(currentNode.getNamespaceURI(), currentNode.getLocalName());
314                 for (SchemaNode childNode : Iterables.concat(list.getChildNodes(), list.getNotifications())) {
315                     if (!list.getKeyDefinition().contains(childNode.getQName())
316                             && currentNodeQName.isEqualWithoutRevision(childNode.getQName())) {
317                         return new AbstractMap.SimpleEntry<>(currentNode, childNode);
318                     }
319                 }
320             }
321         }
322         throw new IllegalStateException("No list child found.");
323     }
324
325     private static NotificationDefinition getMostRecentNotification(
326             final Collection<? extends NotificationDefinition> notificationDefinitions) {
327         return Collections.max(notificationDefinitions, (o1, o2) ->
328             Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
329     }
330
331     @Override
332     public NetconfMessage toRpcRequest(final QName rpc, final NormalizedNode payload) {
333         // In case no input for rpc is defined, we can simply construct the payload here
334
335         // Determine whether a base netconf operation is being invoked
336         // and also check if the device exposed model for base netconf.
337         // If no, use pre built base netconf operations model
338         final boolean needToUseBaseCtx = mappedRpcs.get(rpc) == null && isBaseOrNotificationRpc(rpc);
339         final ImmutableMap<QName, ? extends RpcDefinition> currentMappedRpcs;
340         if (needToUseBaseCtx) {
341             currentMappedRpcs = baseSchema.getMappedRpcs();
342         } else {
343             currentMappedRpcs = mappedRpcs;
344         }
345
346         final RpcDefinition mappedRpc = checkNotNull(currentMappedRpcs.get(rpc),
347                 "Unknown rpc %s, available rpcs: %s", rpc, currentMappedRpcs.keySet());
348         if (mappedRpc.getInput().getChildNodes().isEmpty()) {
349             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpc, counter)
350                 .getNode().getOwnerDocument());
351         }
352
353         checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpc);
354
355         checkArgument(payload instanceof ContainerNode,
356                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpc, payload);
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((ContainerNode) 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 NetconfMessage message, final QName rpc) {
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 NormalizedNodeResult resultHolder = new NormalizedNodeResult();
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 | URISyntaxException | IOException | SAXException e) {
483             throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
484         }
485         return (ContainerNode) resultHolder.getResult();
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.getIdentifier().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 }