9c52523e74ba9c8a64de0b5fae8c2fe4165b7e65
[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     private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
388             final @NonNull RestconfStrategy strategy,
389             final LogicalDatastoreType store, final YangInstanceIdentifier path,
390             final boolean closeTransactionChain) {
391         final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
392         final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = strategy.read(store, path);
393         if (closeTransactionChain) {
394             //Method close transactionChain if any
395             FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
396                     dataFactory, strategy.getTransactionChain());
397         } else {
398             FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
399                     dataFactory);
400         }
401         return dataFactory.build();
402     }
403
404     /**
405      * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
406      * {@link RestconfStrategy} provided as a parameter if any.
407      *
408      * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
409      * @param withDefa with-defaults parameter
410      * @param ctx      schema context
411      * @return {@link NormalizedNode}
412      */
413     private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull RestconfStrategy strategy,
414             final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
415         // PREPARE STATE DATA NODE
416         final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(
417                 strategy, LogicalDatastoreType.OPERATIONAL, path, false);
418
419         // PREPARE CONFIG DATA NODE
420         final NormalizedNode<?, ?> configDataNode;
421         //Here will be closed transactionChain if any
422         if (withDefa == null) {
423             configDataNode = readDataViaTransaction(
424                     strategy, LogicalDatastoreType.CONFIGURATION, path, true);
425         } else {
426             configDataNode = prepareDataByParamWithDef(
427                     readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
428                     path, withDefa, ctx);
429         }
430
431         // if no data exists
432         if (stateDataNode == null && configDataNode == null) {
433             return null;
434         }
435
436         // return config data
437         if (stateDataNode == null) {
438             return configDataNode;
439         }
440
441         // return state data
442         if (configDataNode == null) {
443             return stateDataNode;
444         }
445
446         // merge data from config and state
447         return mergeStateAndConfigData(stateDataNode, configDataNode);
448     }
449
450     /**
451      * Merge state and config data into a single NormalizedNode.
452      *
453      * @param stateDataNode  data node of state data
454      * @param configDataNode data node of config data
455      * @return {@link NormalizedNode}
456      */
457     private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
458             final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
459         validateNodeMerge(stateDataNode, configDataNode);
460         if (configDataNode instanceof RpcDefinition) {
461             return prepareRpcData(configDataNode, stateDataNode);
462         } else {
463             return prepareData(configDataNode, stateDataNode);
464         }
465     }
466
467     /**
468      * Validates whether the two NormalizedNodes can be merged.
469      *
470      * @param stateDataNode  data node of state data
471      * @param configDataNode data node of config data
472      */
473     private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
474                                           final @NonNull NormalizedNode<?, ?> configDataNode) {
475         final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
476         final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
477         if (!moduleOfStateData.equals(moduleOfConfigData)) {
478             throw new RestconfDocumentedException("Unable to merge data from different modules.");
479         }
480     }
481
482     /**
483      * Prepare and map data for rpc.
484      *
485      * @param configDataNode data node of config data
486      * @param stateDataNode  data node of state data
487      * @return {@link NormalizedNode}
488      */
489     private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
490                                                                 final @NonNull NormalizedNode<?, ?> stateDataNode) {
491         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
492                 .mapEntryBuilder();
493         mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
494
495         // MAP CONFIG DATA
496         mapRpcDataNode(configDataNode, mapEntryBuilder);
497         // MAP STATE DATA
498         mapRpcDataNode(stateDataNode, mapEntryBuilder);
499
500         return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
501     }
502
503     /**
504      * Map node to map entry builder.
505      *
506      * @param dataNode        data node
507      * @param mapEntryBuilder builder for mapping data
508      */
509     private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
510             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
511         ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
512     }
513
514     /**
515      * Prepare and map all data from DS.
516      *
517      * @param configDataNode data node of config data
518      * @param stateDataNode  data node of state data
519      * @return {@link NormalizedNode}
520      */
521     @SuppressWarnings("unchecked")
522     private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
523                                                              final @NonNull NormalizedNode<?, ?> stateDataNode) {
524         if (configDataNode instanceof OrderedMapNode) {
525             final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
526                     .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
527
528             mapValueToBuilder(
529                     ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
530
531             return builder.build();
532         } else if (configDataNode instanceof MapNode) {
533             final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
534                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
535
536             mapValueToBuilder(
537                     ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
538
539             return builder.build();
540         } else if (configDataNode instanceof MapEntryNode) {
541             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
542                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
543
544             mapValueToBuilder(
545                     ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
546
547             return builder.build();
548         } else if (configDataNode instanceof ContainerNode) {
549             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
550                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
551
552             mapValueToBuilder(
553                     ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
554
555             return builder.build();
556         } else if (configDataNode instanceof AugmentationNode) {
557             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
558                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
559
560             mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
561                     ((AugmentationNode) stateDataNode).getValue(), builder);
562
563             return builder.build();
564         } else if (configDataNode instanceof ChoiceNode) {
565             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
566                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
567
568             mapValueToBuilder(
569                     ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
570
571             return builder.build();
572         } else if (configDataNode instanceof LeafNode) {
573             return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
574         } else if (configDataNode instanceof OrderedLeafSetNode) {
575             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
576                 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
577
578             mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
579                     ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
580             return builder.build();
581         } else if (configDataNode instanceof LeafSetNode) {
582             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
583                     .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
584
585             mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
586                     ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
587             return builder.build();
588         } else if (configDataNode instanceof LeafSetEntryNode) {
589             return Builders.leafSetEntryBuilder()
590                     .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
591                     .withValue(configDataNode.getValue())
592                     .build();
593         } else if (configDataNode instanceof UnkeyedListNode) {
594             final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
595                     .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
596
597             mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
598                     ((UnkeyedListNode) stateDataNode).getValue(), builder);
599             return builder.build();
600         } else if (configDataNode instanceof UnkeyedListEntryNode) {
601             final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
602                 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
603
604             mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
605                     ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
606             return builder.build();
607         } else {
608             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
609         }
610     }
611
612     /**
613      * Map value from container node to builder.
614      *
615      * @param configData collection of config data nodes
616      * @param stateData  collection of state data nodes
617      * @param builder    builder
618      */
619     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
620             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
621             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
622         final Map<PathArgument, T> configMap = configData.stream().collect(
623                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
624         final Map<PathArgument, T> stateMap = stateData.stream().collect(
625                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
626
627         // merge config and state data of children with different identifiers
628         mapDataToBuilder(configMap, stateMap, builder);
629
630         // merge config and state data of children with the same identifiers
631         mergeDataToBuilder(configMap, stateMap, builder);
632     }
633
634     /**
635      * Map data with different identifiers to builder. Data with different identifiers can be just added
636      * as childs to parent node.
637      *
638      * @param configMap map of config data nodes
639      * @param stateMap  map of state data nodes
640      * @param builder   - builder
641      */
642     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
643             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
644             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
645         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
646             y -> builder.addChild(y.getValue()));
647         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
648             y -> builder.addChild(y.getValue()));
649     }
650
651     /**
652      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
653      * go one level down with {@code prepareData} method.
654      *
655      * @param configMap immutable config data
656      * @param stateMap  immutable state data
657      * @param builder   - builder
658      */
659     @SuppressWarnings("unchecked")
660     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
661             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
662             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
663         // it is enough to process only config data because operational contains the same data
664         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
665             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
666     }
667 }