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