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