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