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