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