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