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