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