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