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