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