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