Bump upstreams for Silicon
[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.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
35 import org.opendaylight.netconf.api.DocumentedException;
36 import org.opendaylight.netconf.api.FailedNetconfMessage;
37 import org.opendaylight.netconf.api.ModifyAction;
38 import org.opendaylight.netconf.api.NetconfDocumentedException;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.api.xml.XmlElement;
41 import org.opendaylight.netconf.api.xml.XmlUtil;
42 import org.opendaylight.netconf.notifications.NetconfNotification;
43 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
44 import org.opendaylight.netconf.util.NetconfUtil;
45 import org.opendaylight.netconf.util.NodeContainerProxy;
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.YangConstants;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
70 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
73 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
74 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
76 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
78 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 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 QName IETF_NETCONF_MONITORING =
107             QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
108     public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
109     public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
110     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
111             QName.create(IETF_NETCONF_MONITORING, "format").intern();
112     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
113             QName.create(IETF_NETCONF_MONITORING, "location").intern();
114     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
115             QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
116     public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
117             QName.create(IETF_NETCONF_MONITORING, "version").intern();
118     public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
119             QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
120
121     public static final QName IETF_NETCONF_NOTIFICATIONS =
122             QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
123
124     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
125
126     public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
127
128     public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
129     public static final NodeIdentifier NETCONF_RPC_REPLY_NODEID = NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
130
131     public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
132     public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
133     public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
134     public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
135     public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
136     public static final NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
137     public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
138     public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
139     public static final NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
140     public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
141     public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
142
143     public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
144     public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
145     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
146     public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
147     public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
148     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
149     public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
150     public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
151
152     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
153     private static final QName NETCONF_OPERATION_QNAME_LEGACY = NETCONF_OPERATION_QNAME.withoutRevision().intern();
154     public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
155             QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
156     public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
157             NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
158     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
159     public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
160     public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
161     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
162     public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
163     public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
164     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
165     public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
166     public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
167     public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
168     public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
169     public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
170     public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
171     public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
172     public static final QName YANG_QNAME = null;
173     public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
174     public static final String NETCONF_ACTION = "action";
175
176     public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
177             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
178     public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
179
180     public static final URI NETCONF_CANDIDATE_URI = URI
181             .create("urn:ietf:params:netconf:capability:candidate:1.0");
182
183     public static final URI NETCONF_NOTIFICATONS_URI = URI
184             .create("urn:ietf:params:netconf:capability:notification:1.0");
185
186     public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
187             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
188
189     public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
190     public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
191     public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
192     public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
193     public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
194     public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
195
196     public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
197
198     // Discard changes message
199     public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
200             .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
201
202     // Commit changes message
203     public static final ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
204             .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
205
206     // Get message
207     public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
208             .withNodeIdentifier(NETCONF_GET_NODEID).build();
209
210     // Create-subscription changes message
211     public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
212             .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
213
214     public static final SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
215
216     public static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
217
218     public static final DataContainerChild<?, ?> EMPTY_FILTER;
219
220     static {
221         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
222                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
223         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
224                 NETCONF_TYPE_QNAME.getLocalName(), SUBTREE);
225
226         EMPTY_FILTER = Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
227                 .withValue(new DOMSource(element)).build();
228     }
229
230     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
231                                                              final EffectiveModelContext ctx) {
232         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
233                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
234         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
235                 SUBTREE);
236
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
243         return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID).withValue(new DOMSource(element))
244                 .build();
245     }
246
247     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
248             throws NetconfDocumentedException {
249         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
250         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
251
252         if (!inputMsgId.equals(outputMsgId)) {
253             final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
254                     .put("actual-message-id", outputMsgId)
255                     .put("expected-message-id", inputMsgId)
256                     .build();
257
258             throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
259                     null, NetconfDocumentedException.ErrorType.PROTOCOL,
260                     NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
261                     NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
262         }
263     }
264
265     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
266         if (NetconfMessageUtil.isErrorMessage(output)) {
267             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
268         }
269     }
270
271     public static RpcError toRpcError(final NetconfDocumentedException ex) {
272         final StringBuilder infoBuilder = new StringBuilder();
273         final Map<String, String> errorInfo = ex.getErrorInfo();
274         if (errorInfo != null) {
275             for (final Entry<String, String> e : errorInfo.entrySet()) {
276                 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
277                         .append("</").append(e.getKey()).append('>');
278
279             }
280         }
281
282         final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
283         return severity == ErrorSeverity.ERROR
284                 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
285                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
286                 : RpcResultBuilder.newWarning(
287                         toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
288                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
289     }
290
291     private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
292         switch (severity) {
293             case WARNING:
294                 return RpcError.ErrorSeverity.WARNING;
295             default:
296                 return RpcError.ErrorSeverity.ERROR;
297         }
298     }
299
300     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
301         switch (type) {
302             case PROTOCOL:
303                 return RpcError.ErrorType.PROTOCOL;
304             case RPC:
305                 return RpcError.ErrorType.RPC;
306             case TRANSPORT:
307                 return RpcError.ErrorType.TRANSPORT;
308             default:
309                 return RpcError.ErrorType.APPLICATION;
310         }
311     }
312
313     public static NodeIdentifier toId(final PathArgument qname) {
314         return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
315     }
316
317     public static NodeIdentifier toId(final QName nodeType) {
318         return new NodeIdentifier(nodeType);
319     }
320
321     public static Element getDataSubtree(final Document doc) {
322         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
323     }
324
325     public static boolean isDataRetrievalOperation(final QName rpc) {
326         return NETCONF_URI.equals(rpc.getNamespace())
327                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
328                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
329     }
330
331     public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
332         return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
333     }
334
335     public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
336         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
337     }
338
339     @Deprecated
340     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
341         return wrap(toId(name), node);
342     }
343
344     public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
345         return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
346     }
347
348     public static DOMSourceAnyxmlNode createEditConfigAnyxml(
349             final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
350             final Optional<ModifyAction> operation,
351             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 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.getValue();
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(
546                         toRpcError(
547                                 new NetconfDocumentedException(
548                                         message.getException().getMessage(),
549                                         DocumentedException.ErrorType.APPLICATION,
550                                         DocumentedException.ErrorTag.MALFORMED_MESSAGE,
551                                         DocumentedException.ErrorSeverity.ERROR)))
552                 .build();
553     }
554 }