Do not instantiate NormalizedNodes for filter
[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 Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
213                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
214         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
215                 "subtree");
216
217         try {
218             NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
219         } catch (IOException | XMLStreamException e) {
220             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
221         }
222         anyXmlBuilder.withValue(new DOMSource(element));
223
224         return anyXmlBuilder.build();
225     }
226
227     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
228             throws NetconfDocumentedException {
229         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
230         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
231
232         if (!inputMsgId.equals(outputMsgId)) {
233             final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
234                     .put("actual-message-id", outputMsgId)
235                     .put("expected-message-id", inputMsgId)
236                     .build();
237
238             throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
239                     null, NetconfDocumentedException.ErrorType.PROTOCOL,
240                     NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
241                     NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
242         }
243     }
244
245     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
246         if (NetconfMessageUtil.isErrorMessage(output)) {
247             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
248         }
249     }
250
251     public static RpcError toRpcError(final NetconfDocumentedException ex) {
252         final StringBuilder infoBuilder = new StringBuilder();
253         final Map<String, String> errorInfo = ex.getErrorInfo();
254         if (errorInfo != null) {
255             for (final Entry<String, String> e : errorInfo.entrySet()) {
256                 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
257                         .append("</").append(e.getKey()).append('>');
258
259             }
260         }
261
262         final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
263         return severity == ErrorSeverity.ERROR
264                 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
265                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
266                 : RpcResultBuilder.newWarning(
267                         toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
268                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
269     }
270
271     private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
272         switch (severity) {
273             case WARNING:
274                 return RpcError.ErrorSeverity.WARNING;
275             default:
276                 return RpcError.ErrorSeverity.ERROR;
277         }
278     }
279
280     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
281         switch (type) {
282             case PROTOCOL:
283                 return RpcError.ErrorType.PROTOCOL;
284             case RPC:
285                 return RpcError.ErrorType.RPC;
286             case TRANSPORT:
287                 return RpcError.ErrorType.TRANSPORT;
288             default:
289                 return RpcError.ErrorType.APPLICATION;
290         }
291     }
292
293     public static NodeIdentifier toId(final PathArgument qname) {
294         return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
295     }
296
297     public static NodeIdentifier toId(final QName nodeType) {
298         return new NodeIdentifier(nodeType);
299     }
300
301     public static Element getDataSubtree(final Document doc) {
302         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
303     }
304
305     public static boolean isDataRetrievalOperation(final QName rpc) {
306         return NETCONF_URI.equals(rpc.getNamespace())
307                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
308                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
309     }
310
311     public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
312         return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
313     }
314
315     public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
316         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
317     }
318
319     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
320         return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
321     }
322
323     public static AnyXmlNode createEditConfigAnyxml(
324             final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
325             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
326         final NormalizedNode<?, ?> configContent;
327
328         if (dataPath.isEmpty()) {
329             Preconditions.checkArgument(lastChildOverride.isPresent(),
330                     "Data has to be present when creating structure for top level element");
331             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
332                     "Data has to be either container or a list node when creating structure for top level element, "
333                             + "but was: %s", lastChildOverride.get());
334             configContent = lastChildOverride.get();
335         } else {
336             final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
337                     ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
338             configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride.toJavaUtil(),
339                 java.util.Optional.ofNullable(modifyOperation));
340         }
341
342         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
343                 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
344         try {
345             NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
346         } catch (IOException | XMLStreamException e) {
347             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
348         }
349
350         return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
351                 .build();
352     }
353
354     public static DataContainerChild<?, ?> createEditConfigStructure(
355             final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
356             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
357         return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
358                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
359     }
360
361     public static SchemaPath toPath(final QName rpc) {
362         return SchemaPath.create(true, rpc);
363     }
364
365     public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
366         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
367         final List<XmlElement> childElements = xmlElement.getChildElements();
368         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
369                 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
370
371         final XmlElement eventTimeElement;
372         final XmlElement notificationElement;
373
374         if (childElements.get(0).getName().equals(EVENT_TIME)) {
375             eventTimeElement = childElements.get(0);
376             notificationElement = childElements.get(1);
377         } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
378             eventTimeElement = childElements.get(1);
379             notificationElement = childElements.get(0);
380         } else {
381             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
382         }
383
384         try {
385             return new AbstractMap.SimpleEntry<>(
386                     NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
387                     notificationElement);
388         } catch (final DocumentedException e) {
389             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
390                     e);
391         } catch (final DateTimeParseException e) {
392             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
393                     NetconfNotification.UNKNOWN_EVENT_TIME, e);
394             return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
395         }
396     }
397
398     public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
399         final Document document = XmlUtil.newDocument();
400         final Element rpcNS =
401                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
402         // set msg id
403         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
404         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
405         rpcNS.appendChild(elementNS);
406         document.appendChild(rpcNS);
407         return new DOMResult(elementNS);
408     }
409
410     public static DOMResult prepareDomResultForActionRequest(DOMDataTreeIdentifier domDataTreeIdentifier,
411             final SchemaPath actionSchemaPath, final MessageCounter counter, String action) {
412         final Document document = XmlUtil.newDocument();
413         final Element rpcNS =
414                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
415         // set msg id
416         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
417
418         final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
419
420         final Element actionData = prepareActionData(actionNS,
421                 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
422
423         Element specificActionElement = document.createElement(action);
424         actionData.appendChild(specificActionElement);
425         rpcNS.appendChild(actionNS);
426         document.appendChild(rpcNS);
427         return new DOMResult(specificActionElement);
428     }
429
430     private static Element prepareActionData(Element actionNS, Iterator<PathArgument> iterator, Document document) {
431         if (iterator.hasNext()) {
432             PathArgument next = iterator.next();
433             final QName actualNS = next.getNodeType();
434
435             final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
436                     actualNS.getLocalName());
437             if (next instanceof NodeWithValue) {
438                 actualElement.setNodeValue(((NodeWithValue) next).getValue().toString());
439             } else if (next instanceof NodeIdentifierWithPredicates) {
440                 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).getKeyValues().entrySet()) {
441                     final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
442                             entry.getKey().getLocalName());
443                     entryElement.setTextContent(entry.getValue().toString());
444                     entryElement.setNodeValue(entry.getValue().toString());
445                     actualElement.appendChild(entryElement);
446                 }
447             }
448             actionNS.appendChild(actualElement);
449             return prepareActionData(actualElement, iterator, document);
450         } else {
451             return actionNS;
452         }
453     }
454
455     @SuppressWarnings("checkstyle:IllegalCatch")
456     public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
457                                           final SchemaPath schemaPath,
458                                           final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
459         final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
460         try {
461             try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
462                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
463                 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
464                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
465                     final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
466                     normalizedNodeWriter.write(value);
467                     normalizedNodeWriter.flush();
468                 }
469             }
470         } finally {
471             try {
472                 writer.close();
473             } catch (final Exception e) {
474                 LOG.warn("Unable to close resource properly", e);
475             }
476         }
477     }
478
479     public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
480         return RpcResultBuilder.<NetconfMessage>failed()
481                 .withRpcError(
482                         toRpcError(
483                                 new NetconfDocumentedException(
484                                         message.getException().getMessage(),
485                                         DocumentedException.ErrorType.APPLICATION,
486                                         DocumentedException.ErrorTag.MALFORMED_MESSAGE,
487                                         DocumentedException.ErrorSeverity.ERROR)))
488                 .build();
489     }
490 }