Reduce the use of AttrBuilders
[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.collect.Iterables;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.FluentFuture;
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.Optional;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
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.LeafSetEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
62 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
69 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
70 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
75 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77
78 /**
79  * Util class for read data from data store via transaction.
80  * <ul>
81  * <li>config
82  * <li>state
83  * <li>all (config + state)
84  * </ul>
85  *
86  */
87 public final class ReadDataTransactionUtil {
88
89     private ReadDataTransactionUtil() {
90         throw new UnsupportedOperationException("Util class.");
91     }
92
93     /**
94      * Parse parameters from URI request and check their types and values.
95      *
96      *
97      * @param identifier
98      *             {@link InstanceIdentifierContext}
99      * @param uriInfo
100      *             URI info
101      * @param tagged
102      *             set tagged for {@link WriterParameters}
103      * @return {@link WriterParameters}
104      */
105     public static @NonNull WriterParameters parseUriParameters(final @NonNull InstanceIdentifierContext<?> identifier,
106             final @Nullable UriInfo uriInfo, final boolean tagged) {
107         return parseParams(identifier, uriInfo, tagged);
108     }
109
110     /**
111      * Parse parameters from URI request and check their types and values.
112      *
113      *
114      * @param identifier
115      *             {@link InstanceIdentifierContext}
116      * @param uriInfo
117      *             URI info
118      * @return {@link WriterParameters}
119      */
120     public static @NonNull WriterParameters parseUriParameters(final @NonNull InstanceIdentifierContext<?> identifier,
121                                                                final @Nullable UriInfo uriInfo) {
122         return parseParams(identifier, uriInfo, false);
123     }
124
125     private static WriterParameters parseParams(final InstanceIdentifierContext<?> identifier, final UriInfo uriInfo,
126             final boolean tagged) {
127         final WriterParametersBuilder builder = new WriterParametersBuilder();
128         builder.setTagged(tagged);
129
130         if (uriInfo == null) {
131             return builder.build();
132         }
133
134         // check only allowed parameters
135         ParametersUtil.checkParametersTypes(
136                 RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
137                 uriInfo.getQueryParameters().keySet(),
138                 RestconfDataServiceConstant.ReadData.CONTENT,
139                 RestconfDataServiceConstant.ReadData.DEPTH,
140                 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
141
142         // read parameters from URI or set default values
143         final List<String> content = uriInfo.getQueryParameters().getOrDefault(
144                 RestconfDataServiceConstant.ReadData.CONTENT,
145                 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
146         final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
147                 RestconfDataServiceConstant.ReadData.DEPTH,
148                 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
149         // fields
150         final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
151                 RestconfDataServiceConstant.ReadData.FIELDS,
152                 Collections.emptyList());
153
154         // parameter can be in URI at most once
155         ParametersUtil.checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
156         ParametersUtil.checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
157         ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
158
159         // check and set content
160         final String contentValue = content.get(0);
161         if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
162             if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
163                     && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
164                 throw new RestconfDocumentedException(
165                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
166                                 "Invalid content parameter: " + contentValue, null,
167                                 "The content parameter value must be either config, nonconfig or all (default)"));
168             }
169         }
170
171         builder.setContent(content.get(0));
172
173         // check and set depth
174         if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
175             final Integer value = Ints.tryParse(depth.get(0));
176
177             if (value == null
178                     || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH
179                         && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) {
180                 throw new RestconfDocumentedException(
181                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
182                                 "Invalid depth parameter: " + depth, null,
183                                 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
184             } else {
185                 builder.setDepth(value);
186             }
187         }
188
189         // check and set fields
190         if (!fields.isEmpty()) {
191             builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
192         }
193
194         return builder.build();
195     }
196
197     /**
198      * Read specific type of data from data store via transaction.
199      *
200      * @param valueOfContent
201      *            type of data to read (config, state, all)
202      * @param transactionNode
203      *            {@link TransactionVarsWrapper} - wrapper for variables
204      * @param schemaContext
205      *            schema context
206      * @return {@link NormalizedNode}
207      */
208     public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
209             final @NonNull TransactionVarsWrapper transactionNode, final SchemaContext schemaContext) {
210         return readData(valueOfContent, transactionNode, null, schemaContext);
211     }
212
213     /**
214      * Read specific type of data from data store via transaction.
215      *
216      * @param valueOfContent
217      *            type of data to read (config, state, all)
218      * @param transactionNode
219      *            {@link TransactionVarsWrapper} - wrapper for variables
220      * @param withDefa
221      *            vaule of with-defaults parameter
222      * @param ctx
223      *            schema context
224      * @return {@link NormalizedNode}
225      */
226     public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
227             final @NonNull TransactionVarsWrapper transactionNode, final String withDefa, final SchemaContext ctx) {
228         switch (valueOfContent) {
229             case RestconfDataServiceConstant.ReadData.CONFIG:
230                 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
231                 if (withDefa == null) {
232                     return readDataViaTransaction(transactionNode);
233                 } else {
234                     return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
235                             transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
236                 }
237             case RestconfDataServiceConstant.ReadData.NONCONFIG:
238                 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
239                 return readDataViaTransaction(transactionNode);
240
241             case RestconfDataServiceConstant.ReadData.ALL:
242                 return readAllData(transactionNode, withDefa, ctx);
243
244             default:
245                 throw new RestconfDocumentedException(
246                         new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
247                                 "Invalid content parameter: " + valueOfContent, null,
248                                 "The content parameter value must be either config, nonconfig or all (default)"));
249         }
250     }
251
252     /**
253      * Read specific type of data from data store via transaction and if identifier read data from
254      * streams then put streams from actual schema context to datastore.
255      *
256      * @param identifier
257      *             identifier of data to read
258      * @param content
259      *             type of data to read (config, state, all)
260      * @param transactionNode
261      *             {@link TransactionVarsWrapper} - wrapper for variables
262      * @param withDefa
263      *             vaule of with-defaults parameter
264      * @param schemaContextRef
265      *             schema context
266      * @param uriInfo
267      *             uri info
268      * @return {@link NormalizedNode}
269      */
270     public static NormalizedNode<?, ?> readData(final String identifier, final String content,
271                                                 final TransactionVarsWrapper transactionNode, final String withDefa,
272                                                 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
273         final SchemaContext schemaContext = schemaContextRef.get();
274         if (identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
275             final DOMDataTreeReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
276             final boolean exist = SubscribeToStreamUtil.checkExist(schemaContext, wTx);
277
278             for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
279                 final List<NotificationListenerAdapter> notifiStreamXML =
280                         CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
281                                 NotificationOutputType.XML.getName());
282                 final List<NotificationListenerAdapter> notifiStreamJSON =
283                         CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
284                                 NotificationOutputType.JSON.getName());
285                 for (final NotificationListenerAdapter listener : Iterables.concat(notifiStreamXML, 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 DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
320                     Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
321             buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
322             return builder.build();
323         } else {
324             final DataContainerNodeBuilder<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 DataContainerNodeBuilder<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 DataContainerNodeBuilder<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 Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
352                 final Object nodeVal = child.getValue();
353                 final NormalizedNodeBuilder<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 DataContainerNodeBuilder<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 DataContainerNodeBuilder<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 DataContainerNodeBuilder<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 Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
407                 final Object nodeVal = child.getValue();
408                 final NormalizedNodeBuilder<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     private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
435             final @NonNull TransactionVarsWrapper transactionNode) {
436         final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
437         try (DOMDataTreeReadTransaction tx = transactionNode.getTransactionChain().newReadOnlyTransaction()) {
438             final FluentFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = tx.read(
439                 transactionNode.getLogicalDatastoreType(),
440                 transactionNode.getInstanceIdentifier().getInstanceIdentifier());
441             FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
442                 dataFactory);
443         }
444         return dataFactory.build();
445     }
446
447     /**
448      * Read config and state data, then map them.
449      *
450      * @param transactionNode
451      *            {@link TransactionVarsWrapper} - wrapper for variables
452      * @param withDefa
453      *            with-defaults parameter
454      * @param ctx
455      *            schema context
456      * @return {@link NormalizedNode}
457      */
458     private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull TransactionVarsWrapper transactionNode,
459             final String withDefa, final SchemaContext ctx) {
460         // PREPARE STATE DATA NODE
461         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
462         final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(transactionNode);
463
464         // PREPARE CONFIG DATA NODE
465         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
466         final NormalizedNode<?, ?> configDataNode;
467         if (withDefa == null) {
468             configDataNode = readDataViaTransaction(transactionNode);
469         } else {
470             configDataNode = prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
471                     transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
472         }
473
474         // if no data exists
475         if (stateDataNode == null && configDataNode == null) {
476             return null;
477         }
478
479         // return config data
480         if (stateDataNode == null) {
481             return configDataNode;
482         }
483
484         // return state data
485         if (configDataNode == null) {
486             return stateDataNode;
487         }
488
489         // merge data from config and state
490         return mergeStateAndConfigData(stateDataNode, configDataNode);
491     }
492
493     /**
494      * Merge state and config data into a single NormalizedNode.
495      *
496      * @param stateDataNode
497      *             data node of state data
498      * @param configDataNode
499      *             data node of config data
500      * @return {@link NormalizedNode}
501      */
502     private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
503             final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
504         validateNodeMerge(stateDataNode, configDataNode);
505         if (configDataNode instanceof RpcDefinition) {
506             return prepareRpcData(configDataNode, stateDataNode);
507         } else {
508             return prepareData(configDataNode, stateDataNode);
509         }
510     }
511
512     /**
513      * Validates whether the two NormalizedNodes can be merged.
514      *
515      * @param stateDataNode
516      *             data node of state data
517      * @param configDataNode
518      *             data node of config data
519      */
520     private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
521                                           final @NonNull NormalizedNode<?, ?> configDataNode) {
522         final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
523         final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
524         if (!moduleOfStateData.equals(moduleOfConfigData)) {
525             throw new RestconfDocumentedException("Unable to merge data from different modules.");
526         }
527     }
528
529     /**
530      * Prepare and map data for rpc.
531      *
532      * @param configDataNode
533      *             data node of config data
534      * @param stateDataNode
535      *             data node of state data
536      * @return {@link NormalizedNode}
537      */
538     private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
539                                                                 final @NonNull 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(final @NonNull NormalizedNode<?, ?> dataNode,
561             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
562         ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
563     }
564
565     /**
566      * Prepare and map all data from DS.
567      *
568      * @param configDataNode
569      *             data node of config data
570      * @param stateDataNode
571      *             data node of state data
572      * @return {@link NormalizedNode}
573      */
574     @SuppressWarnings("unchecked")
575     private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
576                                                              final @NonNull NormalizedNode<?, ?> stateDataNode) {
577         if (configDataNode instanceof OrderedMapNode) {
578             final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
579                     .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
580
581             mapValueToBuilder(
582                     ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
583
584             return builder.build();
585         } else if (configDataNode instanceof MapNode) {
586             final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
587                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
588
589             mapValueToBuilder(
590                     ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
591
592             return builder.build();
593         } else if (configDataNode instanceof MapEntryNode) {
594             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
595                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
596
597             mapValueToBuilder(
598                     ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
599
600             return builder.build();
601         } else if (configDataNode instanceof ContainerNode) {
602             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
603                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
604
605             mapValueToBuilder(
606                     ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
607
608             return builder.build();
609         } else if (configDataNode instanceof AugmentationNode) {
610             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
611                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
612
613             mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
614                     ((AugmentationNode) stateDataNode).getValue(), builder);
615
616             return builder.build();
617         } else if (configDataNode instanceof ChoiceNode) {
618             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
619                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
620
621             mapValueToBuilder(
622                     ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
623
624             return builder.build();
625         } else if (configDataNode instanceof LeafNode) {
626             return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
627         } else if (configDataNode instanceof OrderedLeafSetNode) {
628             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
629                 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
630
631             mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
632                     ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
633             return builder.build();
634         } else if (configDataNode instanceof LeafSetNode) {
635             final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
636                     .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
637
638             mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
639                     ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
640             return builder.build();
641         } else if (configDataNode instanceof UnkeyedListNode) {
642             final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
643                     .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
644
645             mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
646                     ((UnkeyedListNode) stateDataNode).getValue(), builder);
647             return builder.build();
648         } else if (configDataNode instanceof UnkeyedListEntryNode) {
649             final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
650                 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
651
652             mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
653                     ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
654             return builder.build();
655         } else {
656             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
657         }
658     }
659
660     /**
661      * Map value from container node to builder.
662      *
663      * @param configData
664      *             collection of config data nodes
665      * @param stateData
666      *             collection of state data nodes
667      * @param builder
668      *             builder
669      */
670     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
671             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
672             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
673         final Map<PathArgument, T> configMap = configData.stream().collect(
674                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
675         final Map<PathArgument, T> stateMap = stateData.stream().collect(
676                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
677
678         // merge config and state data of children with different identifiers
679         mapDataToBuilder(configMap, stateMap, builder);
680
681         // merge config and state data of children with the same identifiers
682         mergeDataToBuilder(configMap, stateMap, builder);
683     }
684
685     /**
686      * Map data with different identifiers to builder. Data with different identifiers can be just added
687      * as childs to parent node.
688      *
689      * @param configMap
690      *             map of config data nodes
691      * @param stateMap
692      *             map of state data nodes
693      * @param builder
694      *           - builder
695      */
696     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
697             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
698             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
699         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
700             y -> builder.addChild(y.getValue()));
701         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
702             y -> builder.addChild(y.getValue()));
703     }
704
705     /**
706      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
707      * go one level down with {@code prepareData} method.
708      *
709      * @param configMap
710      *             immutable config data
711      * @param stateMap
712      *             immutable state data
713      * @param builder
714      *           - builder
715      */
716     @SuppressWarnings("unchecked")
717     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
718             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
719             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
720         // it is enough to process only config data because operational contains the same data
721         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
722             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
723     }
724 }