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