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