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