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