40ab0b3a49d503cc5de81c935cf544f4b967650f
[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 com.google.common.base.Verify.verifyNotNull;
11 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsParameter;
12 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsPaths;
13
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError;
33 import org.opendaylight.restconf.nb.rfc8040.ContentParameter;
34 import org.opendaylight.restconf.nb.rfc8040.DepthParameter;
35 import org.opendaylight.restconf.nb.rfc8040.FieldsParameter;
36 import org.opendaylight.restconf.nb.rfc8040.WithDefaultsParameter;
37 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
38 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
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.SystemLeafSetNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
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.api.schema.UserLeafSetNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
73 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
76 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
79
80 /**
81  * Util class for read data from data store via transaction.
82  * <ul>
83  * <li>config
84  * <li>state
85  * <li>all (config + state)
86  * </ul>
87  */
88 public final class ReadDataTransactionUtil {
89     private static final Set<String> ALLOWED_PARAMETERS = Set.of(ContentParameter.uriName(), DepthParameter.uriName(),
90         FieldsParameter.uriName(), WithDefaultsParameter.uriName());
91     private static final List<String> POSSIBLE_CONTENT = Arrays.stream(ContentParameter.values())
92         .map(ContentParameter::uriValue)
93         .collect(Collectors.toUnmodifiableList());
94     private static final List<String> POSSIBLE_WITH_DEFAULTS = Arrays.stream(WithDefaultsParameter.values())
95         .map(WithDefaultsParameter::uriValue)
96         .collect(Collectors.toUnmodifiableList());
97
98     private static final String READ_TYPE_TX = "READ";
99
100     private ReadDataTransactionUtil() {
101         // Hidden on purpose
102     }
103
104     /**
105      * Parse parameters from URI request and check their types and values.
106      *
107      * @param identifier {@link InstanceIdentifierContext}
108      * @param uriInfo    URI info
109      * @return {@link QueryParameters}
110      */
111     public static QueryParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
112                                                       final UriInfo uriInfo) {
113         final QueryParameters.Builder builder = QueryParameters.builder();
114         if (uriInfo == null) {
115             return builder.build();
116         }
117
118         // check only allowed parameters
119         final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
120         checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
121
122         // check and set content
123         final String contentStr = getSingleParameter(queryParams, ContentParameter.uriName());
124         if (contentStr != null) {
125             builder.setContent(RestconfDocumentedException.throwIfNull(
126                 ContentParameter.forUriValue(contentStr), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
127                 "Invalid content parameter: %s, allowed values are %s", contentStr, POSSIBLE_CONTENT));
128         }
129
130         // check and set depth
131         final String depthStr = getSingleParameter(queryParams, DepthParameter.uriName());
132         if (depthStr != null) {
133             try {
134                 builder.setDepth(DepthParameter.forUriValue(depthStr));
135             } catch (IllegalArgumentException e) {
136                 throw new RestconfDocumentedException(e, new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
137                     "Invalid depth parameter: " + depthStr, null,
138                     "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
139             }
140         }
141
142         // check and set fields
143         final String fieldsStr = getSingleParameter(queryParams, FieldsParameter.uriName());
144         if (fieldsStr != null) {
145             // FIXME: parse a FieldsParameter instead
146             if (identifier.getMountPoint() != null) {
147                 builder.setFieldPaths(parseFieldsPaths(identifier, fieldsStr));
148             } else {
149                 builder.setFields(parseFieldsParameter(identifier, fieldsStr));
150             }
151         }
152
153         // check and set withDefaults parameter
154         final String withDefaultsStr = getSingleParameter(queryParams, WithDefaultsParameter.uriName());
155         if (withDefaultsStr != null) {
156             final WithDefaultsParameter val = WithDefaultsParameter.forUriValue(withDefaultsStr);
157             if (val == null) {
158                 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
159                     "Invalid with-defaults parameter: " + withDefaultsStr, null,
160                     "The with-defaults parameter must be a string in " + POSSIBLE_WITH_DEFAULTS));
161             }
162
163             switch (val) {
164                 case REPORT_ALL:
165                     break;
166                 case REPORT_ALL_TAGGED:
167                     builder.setTagged(true);
168                     break;
169                 default:
170                     builder.setWithDefault(val);
171             }
172         }
173
174         return builder.build();
175     }
176
177     /**
178      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
179      * inside of object {@link RestconfStrategy} provided as a parameter.
180      *
181      * @param content        type of data to read (config, state, all)
182      * @param path           the path to read
183      * @param strategy       {@link RestconfStrategy} - object that perform the actual DS operations
184      * @param withDefa       value of with-defaults parameter
185      * @param ctx            schema context
186      * @return {@link NormalizedNode}
187      */
188     public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
189                                                     final @NonNull YangInstanceIdentifier path,
190                                                     final @NonNull RestconfStrategy strategy,
191                                                     final WithDefaultsParameter withDefa,
192                                                     final EffectiveModelContext ctx) {
193         // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
194         switch (content) {
195             case ALL:
196                 return readAllData(strategy, path, withDefa, ctx);
197             case CONFIG:
198                 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
199                 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
200             case NONCONFIG:
201                 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
202             default:
203                 throw new RestconfDocumentedException(
204                         new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
205                                 "Invalid content parameter: " + content.uriValue(), null,
206                                 "The content parameter value must be either config, nonconfig or all (default)"));
207         }
208     }
209
210     /**
211      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
212      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
213      *
214      * @param content        type of data to read (config, state, all)
215      * @param path           the parent path to read
216      * @param strategy       {@link RestconfStrategy} - object that perform the actual DS operations
217      * @param withDefa       value of with-defaults parameter
218      * @param ctx            schema context
219      * @param fields         paths to selected subtrees which should be read, relative to to the parent path
220      * @return {@link NormalizedNode}
221      */
222     public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
223             final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
224             final @Nullable WithDefaultsParameter withDefa, @NonNull final EffectiveModelContext ctx,
225             final @NonNull List<YangInstanceIdentifier> fields) {
226         // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
227         switch (content) {
228             case ALL:
229                 return readAllData(strategy, path, withDefa, ctx, fields);
230             case CONFIG:
231                 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
232                     fields);
233                 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
234             case NONCONFIG:
235                 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
236             default:
237                 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
238                         "Invalid content parameter: " + content.uriValue(), null,
239                         "The content parameter value must be either config, nonconfig or all (default)"));
240         }
241     }
242
243     @VisibleForTesting
244     static @Nullable String getSingleParameter(final MultivaluedMap<String, String> params, final String name) {
245         final var values = params.get(name);
246         if (values == null) {
247             return null;
248         }
249
250         switch (values.size()) {
251             case 0:
252                 return null;
253             case 1:
254                 return verifyNotNull(values.get(0));
255             default:
256                 throw new RestconfDocumentedException("Parameter " + name + " can appear at most once in request URI",
257                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
258         }
259     }
260
261     /**
262      * Check if URI does not contain not allowed parameters for specified operation.
263      *
264      * @param usedParameters parameters used in URI request
265      * @param allowedParameters allowed parameters for operation
266      */
267     @VisibleForTesting
268     static void checkParametersTypes(final Set<String> usedParameters, final Set<String> allowedParameters) {
269         if (!allowedParameters.containsAll(usedParameters)) {
270             final Set<String> notAllowedParameters = usedParameters.stream()
271                 .filter(param -> !allowedParameters.contains(param))
272                 .collect(Collectors.toSet());
273             throw new RestconfDocumentedException(
274                 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
275                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
276         }
277     }
278
279     private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
280             final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
281         boolean trim;
282         switch (withDefa) {
283             case TRIM:
284                 trim = true;
285                 break;
286             case EXPLICIT:
287                 trim = false;
288                 break;
289             default:
290                 throw new RestconfDocumentedException("Unsupported with-defaults value " + withDefa.uriValue());
291         }
292
293         final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
294         final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
295         if (result instanceof ContainerNode) {
296             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
297                 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
298             buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
299             return builder.build();
300         } else {
301             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
302                 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
303             buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
304                     ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
305             return builder.build();
306         }
307     }
308
309     private static void buildMapEntryBuilder(
310             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
311             final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
312             final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
313         for (final DataContainerChild child : result.body()) {
314             final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
315             final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
316             if (child instanceof ContainerNode) {
317                 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
318                     SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
319                 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
320                 builder.withChild(childBuilder.build());
321             } else if (child instanceof MapNode) {
322                 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
323                     SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
324                 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
325                         ((ListSchemaNode) childSchema).getKeyDefinition());
326                 builder.withChild(childBuilder.build());
327             } else if (child instanceof LeafNode) {
328                 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
329                 final Object nodeVal = child.body();
330                 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
331                     SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
332                 if (keys.contains(child.getIdentifier().getNodeType())) {
333                     leafBuilder.withValue(((LeafNode<?>) child).body());
334                     builder.withChild(leafBuilder.build());
335                 } else {
336                     if (trim) {
337                         if (defaultVal == null || !defaultVal.equals(nodeVal)) {
338                             leafBuilder.withValue(((LeafNode<?>) child).body());
339                             builder.withChild(leafBuilder.build());
340                         }
341                     } else {
342                         if (defaultVal != null && defaultVal.equals(nodeVal)) {
343                             leafBuilder.withValue(((LeafNode<?>) child).body());
344                             builder.withChild(leafBuilder.build());
345                         }
346                     }
347                 }
348             }
349         }
350     }
351
352     private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
353             final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
354             final boolean trim, final List<QName> keys) {
355         for (final MapEntryNode mapEntryNode : result.body()) {
356             final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
357             final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
358                     .getDataSchemaNode();
359             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
360                 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
361             buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
362             builder.withChild(mapEntryBuilder.build());
363         }
364     }
365
366     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
367             final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
368             final YangInstanceIdentifier actualPath, final boolean trim) {
369         for (final DataContainerChild child : result.body()) {
370             final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
371             final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
372             if (child instanceof ContainerNode) {
373                 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
374                     SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
375                 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
376                 builder.withChild(builderChild.build());
377             } else if (child instanceof MapNode) {
378                 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
379                     SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
380                 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
381                         ((ListSchemaNode) childSchema).getKeyDefinition());
382                 builder.withChild(childBuilder.build());
383             } else if (child instanceof LeafNode) {
384                 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
385                 final Object nodeVal = child.body();
386                 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
387                     SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
388                 if (trim) {
389                     if (defaultVal == null || !defaultVal.equals(nodeVal)) {
390                         leafBuilder.withValue(((LeafNode<?>) child).body());
391                         builder.withChild(leafBuilder.build());
392                     }
393                 } else {
394                     if (defaultVal != null && defaultVal.equals(nodeVal)) {
395                         leafBuilder.withValue(((LeafNode<?>) child).body());
396                         builder.withChild(leafBuilder.build());
397                     }
398                 }
399             }
400         }
401     }
402
403     /**
404      * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
405      * If don't, we have to read all data from DS (state + config)
406      *
407      * @param strategy              {@link RestconfStrategy} - object that perform the actual DS operations
408      * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
409      *                              in {@link RestconfStrategy} if any
410      * @return {@link NormalizedNode}
411      */
412     static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
413             final LogicalDatastoreType store, final YangInstanceIdentifier path) {
414         return extractReadData(strategy, path, strategy.read(store, path));
415     }
416
417     /**
418      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
419      * specified subtrees that should only be read.
420      *
421      * @param strategy              {@link RestconfStrategy} - object that perform the actual DS operations
422      * @param store                 datastore type
423      * @param path                  parent path to selected fields
424      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
425      *                              in {@link RestconfStrategy} if any
426      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
427      * @return {@link NormalizedNode}
428      */
429     private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
430             final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
431             final @NonNull List<YangInstanceIdentifier> fields) {
432         return extractReadData(strategy, path, strategy.read(store, path, fields));
433     }
434
435     private static NormalizedNode extractReadData(final RestconfStrategy strategy,
436             final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
437         final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
438         FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
439         return dataFactory.build();
440     }
441
442     /**
443      * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
444      * {@link RestconfStrategy} provided as a parameter if any.
445      *
446      * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
447      * @param withDefa with-defaults parameter
448      * @param ctx      schema context
449      * @return {@link NormalizedNode}
450      */
451     private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
452             final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
453         // PREPARE STATE DATA NODE
454         final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
455         // PREPARE CONFIG DATA NODE
456         final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
457             path);
458
459         return mergeConfigAndSTateDataIfNeeded(stateDataNode,
460             withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
461     }
462
463     /**
464      * Read config and state data with selected subtrees that should only be read, then map them.
465      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
466      *
467      * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
468      * @param path     parent path to selected fields
469      * @param withDefa with-defaults parameter
470      * @param ctx      schema context
471      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
472      * @return {@link NormalizedNode}
473      */
474     private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
475             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParameter withDefa,
476             final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
477         // PREPARE STATE DATA NODE
478         final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
479             fields);
480
481         // PREPARE CONFIG DATA NODE
482         final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
483             fields);
484         return mergeConfigAndSTateDataIfNeeded(stateDataNode,
485             withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
486     }
487
488     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
489                                                                   final NormalizedNode configDataNode) {
490         // if no data exists
491         if (stateDataNode == null && configDataNode == null) {
492             return null;
493         }
494
495         // return config data
496         if (stateDataNode == null) {
497             return configDataNode;
498         }
499
500         // return state data
501         if (configDataNode == null) {
502             return stateDataNode;
503         }
504
505         // merge data from config and state
506         return mergeStateAndConfigData(stateDataNode, configDataNode);
507     }
508
509     /**
510      * Merge state and config data into a single NormalizedNode.
511      *
512      * @param stateDataNode  data node of state data
513      * @param configDataNode data node of config data
514      * @return {@link NormalizedNode}
515      */
516     private static @NonNull NormalizedNode mergeStateAndConfigData(
517             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
518         validateNodeMerge(stateDataNode, configDataNode);
519         if (configDataNode instanceof RpcDefinition) {
520             return prepareRpcData(configDataNode, stateDataNode);
521         } else {
522             return prepareData(configDataNode, stateDataNode);
523         }
524     }
525
526     /**
527      * Validates whether the two NormalizedNodes can be merged.
528      *
529      * @param stateDataNode  data node of state data
530      * @param configDataNode data node of config data
531      */
532     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
533                                           final @NonNull NormalizedNode configDataNode) {
534         final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
535         final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
536         if (!moduleOfStateData.equals(moduleOfConfigData)) {
537             throw new RestconfDocumentedException("Unable to merge data from different modules.");
538         }
539     }
540
541     /**
542      * Prepare and map data for rpc.
543      *
544      * @param configDataNode data node of config data
545      * @param stateDataNode  data node of state data
546      * @return {@link NormalizedNode}
547      */
548     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
549                                                           final @NonNull NormalizedNode stateDataNode) {
550         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
551                 .mapEntryBuilder();
552         mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
553
554         // MAP CONFIG DATA
555         mapRpcDataNode(configDataNode, mapEntryBuilder);
556         // MAP STATE DATA
557         mapRpcDataNode(stateDataNode, mapEntryBuilder);
558
559         return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
560             .addChild(mapEntryBuilder.build())
561             .build();
562     }
563
564     /**
565      * Map node to map entry builder.
566      *
567      * @param dataNode        data node
568      * @param mapEntryBuilder builder for mapping data
569      */
570     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
571             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
572         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
573     }
574
575     /**
576      * Prepare and map all data from DS.
577      *
578      * @param configDataNode data node of config data
579      * @param stateDataNode  data node of state data
580      * @return {@link NormalizedNode}
581      */
582     @SuppressWarnings("unchecked")
583     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
584                                                        final @NonNull NormalizedNode stateDataNode) {
585         if (configDataNode instanceof UserMapNode) {
586             final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
587                     .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
588
589             mapValueToBuilder(
590                     ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
591
592             return builder.build();
593         } else if (configDataNode instanceof MapNode) {
594             final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
595                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
596
597             mapValueToBuilder(
598                     ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
599
600             return builder.build();
601         } else if (configDataNode instanceof MapEntryNode) {
602             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
603                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
604
605             mapValueToBuilder(
606                     ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
607
608             return builder.build();
609         } else if (configDataNode instanceof ContainerNode) {
610             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
611                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
612
613             mapValueToBuilder(
614                     ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
615
616             return builder.build();
617         } else if (configDataNode instanceof AugmentationNode) {
618             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
619                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
620
621             mapValueToBuilder(((AugmentationNode) configDataNode).body(),
622                     ((AugmentationNode) stateDataNode).body(), builder);
623
624             return builder.build();
625         } else if (configDataNode instanceof ChoiceNode) {
626             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
627                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
628
629             mapValueToBuilder(
630                     ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
631
632             return builder.build();
633         } else if (configDataNode instanceof LeafNode) {
634             return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
635         } else if (configDataNode instanceof UserLeafSetNode) {
636             final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
637                 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
638
639             mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
640                     ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
641             return builder.build();
642         } else if (configDataNode instanceof LeafSetNode) {
643             final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
644                     .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
645
646             mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
647                     ((LeafSetNode<Object>) stateDataNode).body(), builder);
648             return builder.build();
649         } else if (configDataNode instanceof LeafSetEntryNode) {
650             return Builders.leafSetEntryBuilder()
651                     .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
652                     .withValue(configDataNode.body())
653                     .build();
654         } else if (configDataNode instanceof UnkeyedListNode) {
655             final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
656                     .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
657
658             mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
659                     ((UnkeyedListNode) stateDataNode).body(), builder);
660             return builder.build();
661         } else if (configDataNode instanceof UnkeyedListEntryNode) {
662             final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
663                 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
664
665             mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
666                     ((UnkeyedListEntryNode) stateDataNode).body(), builder);
667             return builder.build();
668         } else {
669             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
670         }
671     }
672
673     /**
674      * Map value from container node to builder.
675      *
676      * @param configData collection of config data nodes
677      * @param stateData  collection of state data nodes
678      * @param builder    builder
679      */
680     private static <T extends NormalizedNode> void mapValueToBuilder(
681             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
682             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
683         final Map<PathArgument, T> configMap = configData.stream().collect(
684                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
685         final Map<PathArgument, T> stateMap = stateData.stream().collect(
686                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
687
688         // merge config and state data of children with different identifiers
689         mapDataToBuilder(configMap, stateMap, builder);
690
691         // merge config and state data of children with the same identifiers
692         mergeDataToBuilder(configMap, stateMap, builder);
693     }
694
695     /**
696      * Map data with different identifiers to builder. Data with different identifiers can be just added
697      * as childs to parent node.
698      *
699      * @param configMap map of config data nodes
700      * @param stateMap  map of state data nodes
701      * @param builder   - builder
702      */
703     private static <T extends NormalizedNode> void mapDataToBuilder(
704             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
705             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
706         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
707             y -> builder.addChild(y.getValue()));
708         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
709             y -> builder.addChild(y.getValue()));
710     }
711
712     /**
713      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
714      * go one level down with {@code prepareData} method.
715      *
716      * @param configMap immutable config data
717      * @param stateMap  immutable state data
718      * @param builder   - builder
719      */
720     @SuppressWarnings("unchecked")
721     private static <T extends NormalizedNode> void mergeDataToBuilder(
722             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
723             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
724         // it is enough to process only config data because operational contains the same data
725         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
726             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
727     }
728 }