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