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