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