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