01394503ad3edfd9035b2a5cde78a0b5396f5cc1
[netconf.git] / plugins / netconf-client-mdsal / src / main / java / org / opendaylight / netconf / client / mdsal / impl / NetconfMessageTransformUtil.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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.NETCONF_DATA_QNAME;
12 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.NETCONF_QNAME;
13
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.ImmutableList;
16 import java.io.IOException;
17 import java.time.Instant;
18 import java.time.format.DateTimeParseException;
19 import java.util.ArrayDeque;
20 import java.util.Collection;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Optional;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.stream.XMLStreamWriter;
28 import javax.xml.transform.dom.DOMResult;
29 import javax.xml.transform.dom.DOMSource;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
32 import org.opendaylight.netconf.api.DocumentedException;
33 import org.opendaylight.netconf.api.EffectiveOperation;
34 import org.opendaylight.netconf.api.NamespaceURN;
35 import org.opendaylight.netconf.api.messages.NetconfMessage;
36 import org.opendaylight.netconf.api.messages.NotificationMessage;
37 import org.opendaylight.netconf.api.messages.RpcMessage;
38 import org.opendaylight.netconf.api.messages.RpcReplyMessage;
39 import org.opendaylight.netconf.api.xml.XmlElement;
40 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
41 import org.opendaylight.netconf.api.xml.XmlUtil;
42 import org.opendaylight.netconf.common.mdsal.NormalizedDataUtil;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.XMLNamespace;
49 import org.opendaylight.yangtools.yang.common.YangConstants;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
59 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedMetadata;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
63 import org.opendaylight.yangtools.yang.data.api.schema.stream.YangInstanceIdentifierWriter;
64 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
65 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
66 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedMetadata;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
68 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
70 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
71 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
73 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
74 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
75 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78 import org.w3c.dom.Document;
79 import org.w3c.dom.Element;
80
81 public final class NetconfMessageTransformUtil {
82     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
83
84     public static final String MESSAGE_ID_PREFIX = "m";
85
86     public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
87             QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
88
89     // Blank document used for creation of new DOM nodes
90     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
91
92     public static final @NonNull QName IETF_NETCONF_MONITORING =
93             QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
94     public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
95     public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
96     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
97             QName.create(IETF_NETCONF_MONITORING, "format").intern();
98     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
99             QName.create(IETF_NETCONF_MONITORING, "location").intern();
100     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
101             QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
102     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
103             QName.create(IETF_NETCONF_MONITORING, "version").intern();
104     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
105             QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
106
107     public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
108             QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
109
110     public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
111
112     public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
113
114     public static final @NonNull QName NETCONF_RPC_REPLY_QNAME =
115         QName.create(NETCONF_QNAME, RpcReplyMessage.ELEMENT_NAME).intern();
116     public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
117         NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
118
119     public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, XmlNetconfConstants.OK).intern();
120     public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
121         QName.create(NETCONF_QNAME, "error-option").intern();
122     public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
123         NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
124     public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
125     public static final @NonNull NodeIdentifier NETCONF_RUNNING_NODEID = NodeIdentifier.create(NETCONF_RUNNING_QNAME);
126     public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
127     public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
128     public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
129     public static final @NonNull NodeIdentifier NETCONF_CANDIDATE_NODEID =
130         NodeIdentifier.create(NETCONF_CANDIDATE_QNAME);
131     public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
132     public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
133     public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
134     public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
135
136     public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
137     public static final @NonNull Absolute NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
138     public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
139     public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
140     public static final @NonNull Absolute NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
141     public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
142     public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
143         NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
144     public static final @NonNull Absolute NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
145
146     public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
147     private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
148         NETCONF_OPERATION_QNAME.withoutRevision().intern();
149     public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
150             QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
151     public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
152             NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
153     public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
154     public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
155         NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
156     public static final @NonNull Absolute NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
157     public static final @NonNull QName NETCONF_GET_CONFIG_QNAME =
158         QName.create(NETCONF_QNAME, XmlNetconfConstants.GET_CONFIG).intern();
159     public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
160         NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
161     public static final @NonNull Absolute NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
162     public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
163     public static final @NonNull Absolute NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
164     public static final @NonNull QName NETCONF_GET_QNAME =
165         QName.create(NETCONF_QNAME, XmlNetconfConstants.GET).intern();
166     public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
167     public static final @NonNull Absolute NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
168     public static final @NonNull QName NETCONF_RPC_QNAME =
169         QName.create(NETCONF_QNAME, RpcMessage.ELEMENT_NAME).intern();
170
171     public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
172     public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
173     public static final @NonNull Absolute NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
174     public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
175     public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
176     public static final @NonNull Absolute NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
177
178     public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
179
180     // Discard changes message
181     public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
182             .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
183
184     // Commit changes message
185     public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
186             .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
187
188     // Get message
189     public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
190             .withNodeIdentifier(NETCONF_GET_NODEID).build();
191
192     // Create-subscription changes message
193     public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
194             .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
195
196     public static final @NonNull Absolute CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
197
198     public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID =
199         NodeIdentifier.create(QName.create(NETCONF_QNAME, "filter").intern());
200
201     public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(newFilterElement());
202
203     private NetconfMessageTransformUtil() {
204         // Hidden on purpose
205     }
206
207     /**
208      * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
209      *
210      * @param identifier parent path / query
211      * @param ctx        mountpoint schema context
212      * @return created DOM structure with subtree filter
213      */
214     public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
215                                                        final EffectiveModelContext ctx) {
216         final Element element = newFilterElement();
217         try {
218             NormalizedDataUtil.writeFilter(identifier, new DOMResult(element), ctx, null);
219         } catch (IOException | XMLStreamException e) {
220             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
221         }
222         return buildFilterStructure(element);
223     }
224
225     /**
226      * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
227      * and specific selection fields. Field paths are relative to parent query path.
228      *
229      * @param fieldsFilters list of: parent path and selection fields
230      * @param ctx           mountpoint schema context
231      * @return created DOM structure with subtree filter
232      */
233     public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
234                                                   final EffectiveModelContext ctx) {
235         Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
236         final Element element = newFilterElement();
237
238         for (final FieldsFilter filter : fieldsFilters) {
239             try {
240                 NormalizedDataUtil.writeFilter(filter.path(), new DOMResult(element), ctx, null, filter.fields());
241             } catch (IOException | XMLStreamException e) {
242                 throw new IllegalStateException(String.format(
243                         "Unable to serialize filter element for path %s with fields: %s",
244                         filter.path(), filter.fields()), e);
245             }
246         }
247         return buildFilterStructure(element);
248     }
249
250     private static Element newFilterElement() {
251         final var element = XmlUtil.createElement(BLANK_DOCUMENT, "filter", Optional.of(NamespaceURN.BASE));
252         element.setAttribute("type", "subtree");
253         return element;
254     }
255
256     private static AnyxmlNode<?> buildFilterStructure(final Element element) {
257         return Builders.anyXmlBuilder()
258                 .withNodeIdentifier(NETCONF_FILTER_NODEID)
259                 .withValue(new DOMSource(element))
260                 .build();
261     }
262
263     public static NodeIdentifier toId(final PathArgument arg) {
264         return arg instanceof NodeIdentifier nodeId ? nodeId : toId(arg.getNodeType());
265     }
266
267     public static NodeIdentifier toId(final QName nodeType) {
268         return new NodeIdentifier(nodeType);
269     }
270
271     public static Element getDataSubtree(final Document doc) {
272         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
273     }
274
275     public static boolean isDataRetrievalOperation(final QName rpc) {
276         return NETCONF_URI.equals(rpc.getNamespace())
277                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
278                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
279     }
280
281     @Deprecated
282     public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
283         return wrap(toId(name), node);
284     }
285
286     public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
287         return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
288     }
289
290     /**
291      * Create edit-config structure to invoke {@code operation} with {@code lastChildOverride} data on {@code dataPath}.
292      *
293      * @param ctx {@link EffectiveModelContext} device's model context
294      * @param dataPath {@link YangInstanceIdentifier} path to data in device's data-store
295      * @param operation Optional of {@link EffectiveOperation} action to be invoked
296      * @param lastChildOverride Optional of {@code NormalizedNode} data on which action will be invoked
297      * @return {@link DOMSourceAnyxmlNode} containing edit-config structure
298      */
299     public static DOMSourceAnyxmlNode createEditConfigAnyxml(
300             final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
301             final Optional<EffectiveOperation> operation, final Optional<NormalizedNode> lastChildOverride) {
302         if (dataPath.isEmpty()) {
303             final var override = lastChildOverride.orElseThrow(() -> new IllegalArgumentException(
304                 "Data has to be present when creating structure for top level element"));
305             Preconditions.checkArgument(override instanceof DataContainerChild,
306                 "Data has to be either container or a list node when creating structure for top level element, "
307                     + "but was: %s", override);
308         }
309
310         final var element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
311                 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
312         final var metadata = operation.map(o -> leafMetadata(dataPath, o)).orElse(null);
313         try {
314             if (lastChildOverride.isPresent()) {
315                 // TODO do not transform this into result and then to xml, rework the whole pipeline to directly write
316                 // into xml
317
318                 final var parentPath = dataPath.isEmpty() ? dataPath : dataPath.coerceParent();
319                 var result = new NormalizationResultHolder();
320                 try (var streamWriter = ImmutableNormalizedNodeStreamWriter.from(result)) {
321                     try (var iidWriter = YangInstanceIdentifierWriter.open(streamWriter, ctx, parentPath);
322                          var nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
323                         nnWriter.write(lastChildOverride.orElseThrow());
324                     }
325                 }
326                 NormalizedDataUtil.writeNormalizedNode(result.getResult().data(), metadata, new DOMResult(element), ctx,
327                     null);
328             } else {
329                 NormalizedDataUtil.writeNormalizedNode(dataPath, metadata, new DOMResult(element), ctx, null);
330             }
331         } catch (final IOException | XMLStreamException e) {
332             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
333         }
334
335         return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
336                 .build();
337     }
338
339     private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final EffectiveOperation oper) {
340         record BuilderAndArg(ImmutableNormalizedMetadata.Builder builder, PathArgument arg) {
341             BuilderAndArg {
342                 requireNonNull(builder);
343                 requireNonNull(arg);
344             }
345         }
346
347         final var args = path.getPathArguments();
348         final var builders = new ArrayDeque<BuilderAndArg>(args.size());
349
350         // Step one: open builders
351         for (PathArgument arg : args) {
352             builders.push(new BuilderAndArg(ImmutableNormalizedMetadata.builder(), arg));
353         }
354
355         // Step two: set the top builder's metadata
356         builders.peek().builder.withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.xmlValue());
357
358         // Step three: build the tree
359         while (true) {
360             final var current = builders.pop();
361             final var currentMeta = current.builder.build();
362             final var parent = builders.peek();
363             if (parent != null) {
364                 parent.builder.withChild(current.arg, currentMeta);
365             } else {
366                 return currentMeta;
367             }
368         }
369     }
370
371     public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
372             final YangInstanceIdentifier dataPath, final Optional<EffectiveOperation> operation,
373             final Optional<NormalizedNode> lastChildOverride) {
374         return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
375                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
376     }
377
378     public static @NonNull Absolute toPath(final QName rpc) {
379         return Absolute.of(rpc);
380     }
381
382     public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
383         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
384         final List<XmlElement> childElements = xmlElement.getChildElements();
385         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
386                 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
387
388         final XmlElement eventTimeElement;
389         final XmlElement notificationElement;
390
391         if (childElements.get(0).getName().equals(XmlNetconfConstants.EVENT_TIME)) {
392             eventTimeElement = childElements.get(0);
393             notificationElement = childElements.get(1);
394         } else if (childElements.get(1).getName().equals(XmlNetconfConstants.EVENT_TIME)) {
395             eventTimeElement = childElements.get(1);
396             notificationElement = childElements.get(0);
397         } else {
398             throw new IllegalArgumentException(
399                 "Notification payload does not contain " + XmlNetconfConstants.EVENT_TIME + " " + message);
400         }
401
402         try {
403             return Map.entry(
404                     NotificationMessage.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
405                     notificationElement);
406         } catch (final DocumentedException e) {
407             throw new IllegalArgumentException(
408                 "Notification payload does not contain " + XmlNetconfConstants.EVENT_TIME + " " + message, e);
409         } catch (final DateTimeParseException e) {
410             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
411                 NotificationMessage.UNKNOWN_EVENT_TIME, e);
412             return Map.entry(NotificationMessage.UNKNOWN_EVENT_TIME, notificationElement);
413         }
414     }
415
416     public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
417         final Document document = XmlUtil.newDocument();
418         final Element rpcNS =
419                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
420         // set msg id
421         rpcNS.setAttribute(XmlNetconfConstants.MESSAGE_ID, counter.getNewMessageId(MESSAGE_ID_PREFIX));
422         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
423         rpcNS.appendChild(elementNS);
424         document.appendChild(rpcNS);
425         return new DOMResult(elementNS);
426     }
427
428     public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
429             final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
430         final Document document = XmlUtil.newDocument();
431         final Element rpcNS =
432                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
433         // set msg id
434         rpcNS.setAttribute(XmlNetconfConstants.MESSAGE_ID, counter.getNewMessageId(MESSAGE_ID_PREFIX));
435
436         final Element actionNS = document.createElementNS(YangConstants.RFC6020_YANG_NAMESPACE_STRING, "action");
437         final DataSchemaContext rootSchemaContextNode = dataSchemaContextTree.getRoot();
438         final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
439                 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
440
441         final Element specificActionElement =
442                 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
443         actionData.appendChild(specificActionElement);
444         rpcNS.appendChild(actionNS);
445         document.appendChild(rpcNS);
446         return new DOMResult(specificActionElement);
447     }
448
449     private static Element prepareActionData(final DataSchemaContext currentParentSchemaNode,
450             final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
451         if (iterator.hasNext()) {
452             final PathArgument next = iterator.next();
453
454             final DataSchemaContext current = currentParentSchemaNode instanceof DataSchemaContext.Composite composite
455                 ? composite.childByArg(next) : null;
456             Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
457
458             if (current instanceof PathMixin) {
459                 return prepareActionData(current, actionNS, iterator, document);
460             }
461
462             final QName actualNS = next.getNodeType();
463             final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
464                     actualNS.getLocalName());
465             if (next instanceof NodeWithValue) {
466                 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
467             } else if (next instanceof NodeIdentifierWithPredicates) {
468                 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
469                     final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
470                             entry.getKey().getLocalName());
471                     entryElement.setTextContent(entry.getValue().toString());
472                     entryElement.setNodeValue(entry.getValue().toString());
473                     actualElement.appendChild(entryElement);
474                 }
475             }
476             actionNS.appendChild(actualElement);
477             return prepareActionData(current, actualElement, iterator, document);
478         } else {
479             return actionNS;
480         }
481     }
482
483     public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
484             final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
485                 throws IOException, XMLStreamException {
486         final var stack = SchemaInferenceStack.of(baseNetconfCtx, operationPath);
487         stack.enterSchemaTree(YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule()));
488         final var inputInference = stack.toSchemaTreeInference();
489
490         final XMLStreamWriter writer = NormalizedDataUtil.XML_FACTORY.createXMLStreamWriter(result);
491         try {
492             try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
493                     XMLStreamNormalizedNodeStreamWriter.create(writer, inputInference)) {
494                 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
495                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, inputInference)) {
496                     final Collection<DataContainerChild> value = normalized.body();
497                     normalizedNodeWriter.write(value);
498                     normalizedNodeWriter.flush();
499                 }
500             }
501         } finally {
502             try {
503                 writer.close();
504             } catch (final XMLStreamException e) {
505                 LOG.warn("Unable to close resource properly", e);
506             }
507         }
508     }
509 }