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