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