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