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