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