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