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