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