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