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