Update RFC links
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / utils / ReadDataTransactionUtil.java
1 /*
2  * Copyright (c) 2016 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.restconf.nb.rfc8040.rests.utils;
9
10 import com.google.common.util.concurrent.ListenableFuture;
11 import java.util.Collection;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.NoSuchElementException;
15 import java.util.Optional;
16 import java.util.function.Function;
17 import java.util.stream.Collectors;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
21 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
22 import org.opendaylight.restconf.api.query.ContentParam;
23 import org.opendaylight.restconf.api.query.WithDefaultsParam;
24 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
25 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
48 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
49 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
50 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
51 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
52 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Util class for read data from data store via transaction.
61  * <ul>
62  * <li>config
63  * <li>state
64  * <li>all (config + state)
65  * </ul>
66  */
67 public final class ReadDataTransactionUtil {
68     private static final Logger LOG = LoggerFactory.getLogger(ReadDataTransactionUtil.class);
69
70     private ReadDataTransactionUtil() {
71         // Hidden on purpose
72     }
73
74     /**
75      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
76      * inside of object {@link RestconfStrategy} provided as a parameter.
77      *
78      * @param content        type of data to read (config, state, all)
79      * @param path           the path to read
80      * @param strategy       {@link RestconfStrategy} - object that perform the actual DS operations
81      * @param withDefa       value of with-defaults parameter
82      * @param ctx            schema context
83      * @return {@link NormalizedNode}
84      */
85     public static @Nullable NormalizedNode readData(final @NonNull ContentParam content,
86                                                     final @NonNull YangInstanceIdentifier path,
87                                                     final @NonNull RestconfStrategy strategy,
88                                                     final WithDefaultsParam withDefa,
89                                                     final EffectiveModelContext ctx) {
90         return switch (content) {
91             case ALL -> readAllData(strategy, path, withDefa, ctx);
92             case CONFIG -> {
93                 final var read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
94                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
95             }
96             case NONCONFIG -> readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
97         };
98     }
99
100     /**
101      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
102      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
103      *
104      * @param content        type of data to read (config, state, all)
105      * @param path           the parent path to read
106      * @param strategy       {@link RestconfStrategy} - object that perform the actual DS operations
107      * @param withDefa       value of with-defaults parameter
108      * @param ctx            schema context
109      * @param fields         paths to selected subtrees which should be read, relative to to the parent path
110      * @return {@link NormalizedNode}
111      */
112     public static @Nullable NormalizedNode readData(final @NonNull ContentParam content,
113             final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
114             final @Nullable WithDefaultsParam withDefa, @NonNull final EffectiveModelContext ctx,
115             final @NonNull List<YangInstanceIdentifier> fields) {
116         return switch (content) {
117             case ALL -> readAllData(strategy, path, withDefa, ctx, fields);
118             case CONFIG -> {
119                 final var read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, fields);
120                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
121             }
122             case NONCONFIG -> readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
123         };
124     }
125
126     private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
127             final YangInstanceIdentifier path, final WithDefaultsParam withDefa, final EffectiveModelContext ctx) {
128         final boolean trim = switch (withDefa) {
129             case TRIM -> true;
130             case EXPLICIT -> false;
131             case REPORT_ALL, REPORT_ALL_TAGGED -> throw new RestconfDocumentedException(
132                 "Unsupported with-defaults value " + withDefa.paramValue());
133         };
134
135         final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
136         if (readData instanceof ContainerNode container) {
137             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
138             buildCont(builder, container.body(), ctxNode, trim);
139             return builder.build();
140         } else if (readData instanceof MapEntryNode mapEntry) {
141             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
142                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
143             }
144
145             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
146             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
147             return builder.build();
148         } else {
149             throw new IllegalStateException("Unhandled data contract " + readData.contract());
150         }
151     }
152
153     private static void buildMapEntryBuilder(
154             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
155             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
156             final boolean trim, final List<QName> keys) {
157         for (var child : children) {
158             final var childCtx = getChildContext(ctxNode, child);
159
160             if (child instanceof ContainerNode container) {
161                 appendContainer(builder, container, childCtx, trim);
162             } else if (child instanceof MapNode map) {
163                 appendMap(builder, map, childCtx, trim);
164             } else if (child instanceof LeafNode<?> leaf) {
165                 appendLeaf(builder, leaf, childCtx, trim, keys);
166             } else {
167                 // FIXME: we should never hit this, throw an ISE if this ever happens
168                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
169             }
170         }
171     }
172
173     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
174             final DataSchemaContext ctxNode, final boolean trim) {
175         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
176         buildCont(childBuilder, container.body(), ctxNode, trim);
177         builder.withChild(childBuilder.build());
178     }
179
180     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
181             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
182         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
183             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
184         }
185
186         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
187         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
188
189         // This is a combined check for when we need to emit the leaf.
190         if (
191             // We always have to emit key leaf values
192             keys.contains(leafSchema.getQName())
193             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
194             //
195             //            When data is retrieved with a <with-defaults> parameter equal to
196             //            'trim', data nodes MUST NOT be reported if they contain the schema
197             //            default value.  Non-configuration data nodes containing the schema
198             //            default value MUST NOT be reported.
199             //
200             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
201             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
202             // grasp what we are doing here... emit only if it matches default ???!!!
203             // FIXME: The WithDefaultsParam.EXPLICIT says:
204             //
205             //            Data nodes set to the YANG default by the client are reported.
206             //
207             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
208             //
209             //            If the "with-defaults" parameter is set to "explicit", then the
210             //            server MUST adhere to the default-reporting behavior defined in
211             //            Section 3.3 of [RFC6243].
212             //
213             //        and then RFC6243 says:
214             //
215             //            When data is retrieved with a <with-defaults> parameter equal to
216             //            'explicit', a data node that was set by a client to its schema
217             //            default value MUST be reported.  A conceptual data node that would be
218             //            set by the server to the schema default value MUST NOT be reported.
219             //            Non-configuration data nodes containing the schema default value MUST
220             //            be reported.
221             //
222             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
223             //            This seems to disregard the 'trim = true' case semantics (see above).
224             //            Combining the above, though, these checks are missing the 'non-config' check, which would
225             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
226             //            Without that input, this really should be  covered by the previous case.
227                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
228             builder.withChild(leaf);
229         }
230     }
231
232     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
233             final DataSchemaContext childCtx, final boolean trim) {
234         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
235             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
236         }
237
238         final var childBuilder = switch (map.ordering()) {
239             case SYSTEM -> Builders.mapBuilder();
240             case USER -> Builders.orderedMapBuilder();
241         };
242         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
243             listSchema.getKeyDefinition());
244         builder.withChild(childBuilder.build());
245     }
246
247     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
248             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
249             final List<@NonNull QName> keys) {
250         for (var entry : entries) {
251             final var childCtx = getChildContext(ctxNode, entry);
252             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
253             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
254             builder.withChild(mapEntryBuilder.build());
255         }
256     }
257
258     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
259             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
260         for (var child : children) {
261             final var childCtx = getChildContext(ctxNode, child);
262             if (child instanceof ContainerNode container) {
263                 appendContainer(builder, container, childCtx, trim);
264             } else if (child instanceof MapNode map) {
265                 appendMap(builder, map, childCtx, trim);
266             } else if (child instanceof LeafNode<?> leaf) {
267                 appendLeaf(builder, leaf, childCtx, trim, List.of());
268             }
269         }
270     }
271
272     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
273             final NormalizedNode child) {
274         final var childId = child.name();
275         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
276             : null;
277         if (childCtx == null) {
278             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
279         }
280         return childCtx;
281     }
282
283     /**
284      * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
285      * If don't, we have to read all data from DS (state + config)
286      *
287      * @param strategy              {@link RestconfStrategy} - object that perform the actual DS operations
288      * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
289      *                              in {@link RestconfStrategy} if any
290      * @return {@link NormalizedNode}
291      */
292     static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
293             final LogicalDatastoreType store, final YangInstanceIdentifier path) {
294         return extractReadData(strategy, path, strategy.read(store, path));
295     }
296
297     /**
298      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
299      * specified subtrees that should only be read.
300      *
301      * @param strategy              {@link RestconfStrategy} - object that perform the actual DS operations
302      * @param store                 datastore type
303      * @param path                  parent path to selected fields
304      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
305      *                              in {@link RestconfStrategy} if any
306      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
307      * @return {@link NormalizedNode}
308      */
309     private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
310             final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
311             final @NonNull List<YangInstanceIdentifier> fields) {
312         return extractReadData(strategy, path, strategy.read(store, path, fields));
313     }
314
315     private static NormalizedNode extractReadData(final RestconfStrategy strategy,
316             final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
317         final var dataFactory = new NormalizedNodeFactory();
318         FutureCallbackTx.addCallback(dataFuture, "READ", dataFactory, path);
319         return dataFactory.build();
320     }
321
322     /**
323      * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
324      * {@link RestconfStrategy} provided as a parameter if any.
325      *
326      * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
327      * @param withDefa with-defaults parameter
328      * @param ctx      schema context
329      * @return {@link NormalizedNode}
330      */
331     private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
332             final YangInstanceIdentifier path, final WithDefaultsParam withDefa, final EffectiveModelContext ctx) {
333         // PREPARE STATE DATA NODE
334         final var stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
335         // PREPARE CONFIG DATA NODE
336         final var configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
337
338         return mergeConfigAndSTateDataIfNeeded(stateDataNode,
339             withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
340     }
341
342     /**
343      * Read config and state data with selected subtrees that should only be read, then map them.
344      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
345      *
346      * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
347      * @param path     parent path to selected fields
348      * @param withDefa with-defaults parameter
349      * @param ctx      schema context
350      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
351      * @return {@link NormalizedNode}
352      */
353     private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
354             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
355             final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
356         // PREPARE STATE DATA NODE
357         final var stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
358         // PREPARE CONFIG DATA NODE
359         final var configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, fields);
360
361         return mergeConfigAndSTateDataIfNeeded(stateDataNode,
362             withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
363     }
364
365     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
366                                                                   final NormalizedNode configDataNode) {
367         // if no data exists
368         if (stateDataNode == null && configDataNode == null) {
369             return null;
370         }
371
372         // return config data
373         if (stateDataNode == null) {
374             return configDataNode;
375         }
376
377         // return state data
378         if (configDataNode == null) {
379             return stateDataNode;
380         }
381
382         // merge data from config and state
383         return mergeStateAndConfigData(stateDataNode, configDataNode);
384     }
385
386     /**
387      * Merge state and config data into a single NormalizedNode.
388      *
389      * @param stateDataNode  data node of state data
390      * @param configDataNode data node of config data
391      * @return {@link NormalizedNode}
392      */
393     private static @NonNull NormalizedNode mergeStateAndConfigData(
394             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
395         validateNodeMerge(stateDataNode, configDataNode);
396         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
397         if (configDataNode instanceof RpcDefinition) {
398             return prepareRpcData(configDataNode, stateDataNode);
399         } else {
400             return prepareData(configDataNode, stateDataNode);
401         }
402     }
403
404     /**
405      * Validates whether the two NormalizedNodes can be merged.
406      *
407      * @param stateDataNode  data node of state data
408      * @param configDataNode data node of config data
409      */
410     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
411                                           final @NonNull NormalizedNode configDataNode) {
412         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
413         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
414         if (!moduleOfStateData.equals(moduleOfConfigData)) {
415             throw new RestconfDocumentedException("Unable to merge data from different modules.");
416         }
417     }
418
419     /**
420      * Prepare and map data for rpc.
421      *
422      * @param configDataNode data node of config data
423      * @param stateDataNode  data node of state data
424      * @return {@link NormalizedNode}
425      */
426     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
427                                                           final @NonNull NormalizedNode stateDataNode) {
428         final var mapEntryBuilder = Builders.mapEntryBuilder()
429             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
430
431         // MAP CONFIG DATA
432         mapRpcDataNode(configDataNode, mapEntryBuilder);
433         // MAP STATE DATA
434         mapRpcDataNode(stateDataNode, mapEntryBuilder);
435
436         return Builders.mapBuilder()
437             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
438             .addChild(mapEntryBuilder.build())
439             .build();
440     }
441
442     /**
443      * Map node to map entry builder.
444      *
445      * @param dataNode        data node
446      * @param mapEntryBuilder builder for mapping data
447      */
448     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
449             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
450         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
451     }
452
453     /**
454      * Prepare and map all data from DS.
455      *
456      * @param configDataNode data node of config data
457      * @param stateDataNode  data node of state data
458      * @return {@link NormalizedNode}
459      */
460     @SuppressWarnings("unchecked")
461     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
462                                                        final @NonNull NormalizedNode stateDataNode) {
463         if (configDataNode instanceof UserMapNode configMap) {
464             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
465             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
466             return builder.build();
467         } else if (configDataNode instanceof SystemMapNode configMap) {
468             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
469             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
470             return builder.build();
471         } else if (configDataNode instanceof MapEntryNode configEntry) {
472             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
473             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
474             return builder.build();
475         } else if (configDataNode instanceof ContainerNode configContaienr) {
476             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
477             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
478             return builder.build();
479         } else if (configDataNode instanceof ChoiceNode configChoice) {
480             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
481             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
482             return builder.build();
483         } else if (configDataNode instanceof LeafNode configLeaf) {
484             // config trumps oper
485             return configLeaf;
486         } else if (configDataNode instanceof UserLeafSetNode) {
487             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
488             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
489             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
490             return builder.build();
491         } else if (configDataNode instanceof SystemLeafSetNode) {
492             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
493             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
494             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
495             return builder.build();
496         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
497             // config trumps oper
498             return configEntry;
499         } else if (configDataNode instanceof UnkeyedListNode configList) {
500             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
501             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
502             return builder.build();
503         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
504             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
505             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
506             return builder.build();
507         } else {
508             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
509         }
510     }
511
512     /**
513      * Map value from container node to builder.
514      *
515      * @param configData collection of config data nodes
516      * @param stateData  collection of state data nodes
517      * @param builder    builder
518      */
519     private static <T extends NormalizedNode> void mapValueToBuilder(
520             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
521             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
522         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
523         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
524
525         // merge config and state data of children with different identifiers
526         mapDataToBuilder(configMap, stateMap, builder);
527
528         // merge config and state data of children with the same identifiers
529         mergeDataToBuilder(configMap, stateMap, builder);
530     }
531
532     /**
533      * Map data with different identifiers to builder. Data with different identifiers can be just added
534      * as childs to parent node.
535      *
536      * @param configMap map of config data nodes
537      * @param stateMap  map of state data nodes
538      * @param builder   - builder
539      */
540     private static <T extends NormalizedNode> void mapDataToBuilder(
541             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
542             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
543         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
544             y -> builder.addChild(y.getValue()));
545         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
546             y -> builder.addChild(y.getValue()));
547     }
548
549     /**
550      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
551      * go one level down with {@code prepareData} method.
552      *
553      * @param configMap immutable config data
554      * @param stateMap  immutable state data
555      * @param builder   - builder
556      */
557     @SuppressWarnings("unchecked")
558     private static <T extends NormalizedNode> void mergeDataToBuilder(
559             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
560             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
561         // it is enough to process only config data because operational contains the same data
562         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
563             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
564     }
565 }