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