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