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