Implement NodeContainerProxy.getPath()
[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 static org.opendaylight.netconf.util.NetconfUtil.NETCONF_DATA_QNAME;
11 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_QNAME;
12
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import java.io.IOException;
17 import java.net.URI;
18 import java.time.Instant;
19 import java.time.format.DateTimeParseException;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.ArrayDeque;
22 import java.util.Collection;
23 import java.util.Deque;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Locale;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.stream.XMLStreamWriter;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
36 import org.opendaylight.netconf.api.DocumentedException;
37 import org.opendaylight.netconf.api.FailedNetconfMessage;
38 import org.opendaylight.netconf.api.ModifyAction;
39 import org.opendaylight.netconf.api.NetconfDocumentedException;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.XmlElement;
42 import org.opendaylight.netconf.api.xml.XmlUtil;
43 import org.opendaylight.netconf.notifications.NetconfNotification;
44 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
45 import org.opendaylight.netconf.util.NetconfUtil;
46 import org.opendaylight.netconf.util.NodeContainerProxy;
47 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
52 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
53 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
54 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
60 import org.opendaylight.yangtools.yang.common.YangConstants;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
66 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
71 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
72 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
73 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
74 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
76 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
79 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
80 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
81 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.Document;
85 import org.w3c.dom.Element;
86
87 public final class NetconfMessageTransformUtil {
88
89     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
90
91     public static final String MESSAGE_ID_PREFIX = "m";
92     public static final String MESSAGE_ID_ATTR = "message-id";
93
94     public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
95             QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
96     private static final String SUBTREE = "subtree";
97
98     // Blank document used for creation of new DOM nodes
99     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
100     public static final String EVENT_TIME = "eventTime";
101
102     private NetconfMessageTransformUtil() {
103
104     }
105
106     public static final @NonNull QName IETF_NETCONF_MONITORING =
107             QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
108     public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
109     public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
110     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
111             QName.create(IETF_NETCONF_MONITORING, "format").intern();
112     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
113             QName.create(IETF_NETCONF_MONITORING, "location").intern();
114     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
115             QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
116     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
117             QName.create(IETF_NETCONF_MONITORING, "version").intern();
118     public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
119             QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
120
121     public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
122             QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
123
124     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
125
126     public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
127
128     public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
129     public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
130         NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
131
132     public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
133     public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
134         QName.create(NETCONF_QNAME, "error-option").intern();
135     public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
136         NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
137     public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
138     public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
139     public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
140     public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
141     public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
142     public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
143     public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
144     public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
145
146     public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
147     public static final @NonNull SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
148     public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
149     public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
150     public static final @NonNull SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
151     public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
152     public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
153         NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
154     public static final @NonNull SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
155
156     public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
157     private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
158         NETCONF_OPERATION_QNAME.withoutRevision().intern();
159     public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
160             QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
161     public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
162             NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
163     public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
164     public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
165         NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
166     public static final @NonNull SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
167     public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
168     public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
169         NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
170     public static final @NonNull SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
171     public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
172     public static final @NonNull SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
173     public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
174     public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
175     public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
176     public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
177     public static final @NonNull SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
178     public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
179     public static final QName YANG_QNAME = null;
180     public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
181     public static final String NETCONF_ACTION = "action";
182
183     public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
184             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
185     public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
186
187     public static final URI NETCONF_CANDIDATE_URI = URI
188             .create("urn:ietf:params:netconf:capability:candidate:1.0");
189
190     public static final URI NETCONF_NOTIFICATONS_URI = URI
191             .create("urn:ietf:params:netconf:capability:notification:1.0");
192
193     public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
194             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
195
196     public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
197     public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
198     public static final @NonNull SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
199     public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
200     public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
201     public static final @NonNull SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
202
203     public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
204
205     // Discard changes message
206     public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
207             .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
208
209     // Commit changes message
210     public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
211             .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
212
213     // Get message
214     public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
215             .withNodeIdentifier(NETCONF_GET_NODEID).build();
216
217     // Create-subscription changes message
218     public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
219             .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
220
221     public static final @NonNull SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
222
223     public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
224
225     public static final @NonNull DataContainerChild<?, ?> EMPTY_FILTER;
226
227     static {
228         final Element element = getNetconfFilterElement();
229         EMPTY_FILTER = buildFilterStructure(element);
230     }
231
232     /**
233      * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
234      *
235      * @param identifier parent path / query
236      * @param ctx        mountpoint schema context
237      * @return created DOM structure with subtree filter
238      */
239     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
240                                                              final EffectiveModelContext ctx) {
241         final Element element = getNetconfFilterElement();
242         try {
243             NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
244         } catch (IOException | XMLStreamException e) {
245             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
246         }
247         return buildFilterStructure(element);
248     }
249
250     /**
251      * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
252      * and specific selection fields. Field paths are relative to parent query path.
253      *
254      * @param fieldsFilters list of: parent path and selection fields
255      * @param ctx           mountpoint schema context
256      * @return created DOM structure with subtree filter
257      */
258     public static DataContainerChild<?, ?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
259                                                              final EffectiveModelContext ctx) {
260         Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
261         final Element element = getNetconfFilterElement();
262
263         for (final FieldsFilter filter : fieldsFilters) {
264             try {
265                 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), SchemaPath.ROOT, ctx, filter.fields());
266             } catch (IOException | XMLStreamException e) {
267                 throw new IllegalStateException(String.format(
268                         "Unable to serialize filter element for path %s with fields: %s",
269                         filter.path(), filter.fields()), e);
270             }
271         }
272         return buildFilterStructure(element);
273     }
274
275     private static Element getNetconfFilterElement() {
276         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
277                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
278         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
279                 SUBTREE);
280         return element;
281     }
282
283     private static DataContainerChild<?, ?> buildFilterStructure(final Element element) {
284         return Builders.anyXmlBuilder()
285                 .withNodeIdentifier(NETCONF_FILTER_NODEID)
286                 .withValue(new DOMSource(element))
287                 .build();
288     }
289
290     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
291             throws NetconfDocumentedException {
292         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
293         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
294
295         if (!inputMsgId.equals(outputMsgId)) {
296             final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
297                     .put("actual-message-id", outputMsgId)
298                     .put("expected-message-id", inputMsgId)
299                     .build();
300
301             throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
302                     null, NetconfDocumentedException.ErrorType.PROTOCOL,
303                     NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
304                     NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
305         }
306     }
307
308     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
309         if (NetconfMessageUtil.isErrorMessage(output)) {
310             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
311         }
312     }
313
314     public static RpcError toRpcError(final NetconfDocumentedException ex) {
315         final StringBuilder infoBuilder = new StringBuilder();
316         final Map<String, String> errorInfo = ex.getErrorInfo();
317         if (errorInfo != null) {
318             for (final Entry<String, String> e : errorInfo.entrySet()) {
319                 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
320                         .append("</").append(e.getKey()).append('>');
321
322             }
323         }
324
325         final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
326         return severity == ErrorSeverity.ERROR
327                 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
328                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
329                 : RpcResultBuilder.newWarning(
330                         toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
331                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
332     }
333
334     private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
335         switch (severity) {
336             case WARNING:
337                 return RpcError.ErrorSeverity.WARNING;
338             default:
339                 return RpcError.ErrorSeverity.ERROR;
340         }
341     }
342
343     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
344         switch (type) {
345             case PROTOCOL:
346                 return RpcError.ErrorType.PROTOCOL;
347             case RPC:
348                 return RpcError.ErrorType.RPC;
349             case TRANSPORT:
350                 return RpcError.ErrorType.TRANSPORT;
351             default:
352                 return RpcError.ErrorType.APPLICATION;
353         }
354     }
355
356     public static NodeIdentifier toId(final PathArgument qname) {
357         return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
358     }
359
360     public static NodeIdentifier toId(final QName nodeType) {
361         return new NodeIdentifier(nodeType);
362     }
363
364     public static Element getDataSubtree(final Document doc) {
365         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
366     }
367
368     public static boolean isDataRetrievalOperation(final QName rpc) {
369         return NETCONF_URI.equals(rpc.getNamespace())
370                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
371                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
372     }
373
374     public static @NonNull ContainerSchemaNode createSchemaForDataRead(final EffectiveModelContext schemaContext) {
375         return NodeContainerProxy.ofModelContext(NETCONF_DATA_QNAME, schemaContext);
376     }
377
378     public static @NonNull ContainerSchemaNode createSchemaForNotification(final NotificationDefinition notification) {
379         return NodeContainerProxy.ofNotification(notification);
380     }
381
382     @Deprecated
383     public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
384         return wrap(toId(name), node);
385     }
386
387     public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
388         return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
389     }
390
391     public static DOMSourceAnyxmlNode createEditConfigAnyxml(
392             final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
393             final Optional<ModifyAction> operation,
394             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
395         final NormalizedNode<?, ?> configContent;
396         final NormalizedMetadata metadata;
397         if (dataPath.isEmpty()) {
398             Preconditions.checkArgument(lastChildOverride.isPresent(),
399                     "Data has to be present when creating structure for top level element");
400             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
401                     "Data has to be either container or a list node when creating structure for top level element, "
402                             + "but was: %s", lastChildOverride.get());
403             configContent = lastChildOverride.get();
404             metadata = null;
405         } else {
406             configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
407             metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
408         }
409
410         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
411                 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
412
413         try {
414             NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
415         } catch (IOException | XMLStreamException e) {
416             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
417         }
418
419         return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
420                 .build();
421     }
422
423     private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
424         final List<PathArgument> args = path.getPathArguments();
425         final Deque<Builder> builders = new ArrayDeque<>(args.size());
426
427         // Step one: open builders
428         for (PathArgument arg : args) {
429             builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
430         }
431
432         // Step two: set the top builder's metadata
433         builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
434
435         // Step three: build the tree
436         while (true) {
437             final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
438             final Builder parent = builders.peek();
439             if (parent != null) {
440                 parent.withChild(currentMeta);
441             } else {
442                 return currentMeta;
443             }
444         }
445     }
446
447     public static DataContainerChild<?, ?> createEditConfigStructure(final EffectiveModelContext ctx,
448             final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
449             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
450         return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
451                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
452     }
453
454     public static @NonNull SchemaPath toPath(final QName rpc) {
455         return SchemaPath.ROOT.createChild(rpc);
456     }
457
458     public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
459         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
460         final List<XmlElement> childElements = xmlElement.getChildElements();
461         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
462                 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
463
464         final XmlElement eventTimeElement;
465         final XmlElement notificationElement;
466
467         if (childElements.get(0).getName().equals(EVENT_TIME)) {
468             eventTimeElement = childElements.get(0);
469             notificationElement = childElements.get(1);
470         } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
471             eventTimeElement = childElements.get(1);
472             notificationElement = childElements.get(0);
473         } else {
474             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
475         }
476
477         try {
478             return new SimpleEntry<>(
479                     NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
480                     notificationElement);
481         } catch (final DocumentedException e) {
482             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
483                     e);
484         } catch (final DateTimeParseException e) {
485             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
486                     NetconfNotification.UNKNOWN_EVENT_TIME, e);
487             return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
488                     notificationElement);
489         }
490     }
491
492     public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
493         final Document document = XmlUtil.newDocument();
494         final Element rpcNS =
495                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
496         // set msg id
497         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
498         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
499         rpcNS.appendChild(elementNS);
500         document.appendChild(rpcNS);
501         return new DOMResult(elementNS);
502     }
503
504     public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
505             final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
506         final Document document = XmlUtil.newDocument();
507         final Element rpcNS =
508                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
509         // set msg id
510         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
511
512         final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
513         final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
514         final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
515                 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
516
517         final Element specificActionElement =
518                 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
519         actionData.appendChild(specificActionElement);
520         rpcNS.appendChild(actionNS);
521         document.appendChild(rpcNS);
522         return new DOMResult(specificActionElement);
523     }
524
525     private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
526             final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
527         if (iterator.hasNext()) {
528             final PathArgument next = iterator.next();
529
530             final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
531             Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
532
533             if (current.isMixin()) {
534                 return prepareActionData(current, actionNS, iterator, document);
535             }
536
537             final QName actualNS = next.getNodeType();
538             final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
539                     actualNS.getLocalName());
540             if (next instanceof NodeWithValue) {
541                 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
542             } else if (next instanceof NodeIdentifierWithPredicates) {
543                 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
544                     final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
545                             entry.getKey().getLocalName());
546                     entryElement.setTextContent(entry.getValue().toString());
547                     entryElement.setNodeValue(entry.getValue().toString());
548                     actualElement.appendChild(entryElement);
549                 }
550             }
551             actionNS.appendChild(actualElement);
552             return prepareActionData(current, actualElement, iterator, document);
553         } else {
554             return actionNS;
555         }
556     }
557
558     @SuppressWarnings("checkstyle:IllegalCatch")
559     public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
560             final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
561                 throws IOException, XMLStreamException {
562         final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
563         // FIXME: eliminate this conversion
564         final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
565
566         final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
567         try {
568             try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
569                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
570                 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
571                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
572                     final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
573                     normalizedNodeWriter.write(value);
574                     normalizedNodeWriter.flush();
575                 }
576             }
577         } finally {
578             try {
579                 writer.close();
580             } catch (final Exception e) {
581                 LOG.warn("Unable to close resource properly", e);
582             }
583         }
584     }
585
586     public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
587         return RpcResultBuilder.<NetconfMessage>failed()
588                 .withRpcError(
589                         toRpcError(
590                                 new NetconfDocumentedException(
591                                         message.getException().getMessage(),
592                                         DocumentedException.ErrorType.APPLICATION,
593                                         DocumentedException.ErrorTag.MALFORMED_MESSAGE,
594                                         DocumentedException.ErrorSeverity.ERROR)))
595                 .build();
596     }
597 }