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