2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.utils;
10 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsParameter;
11 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsPaths;
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;
19 import java.util.Optional;
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;
78 * Util class for read data from data store via transaction.
82 * <li>all (config + state)
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";
95 private ReadDataTransactionUtil() {
100 * Parse parameters from URI request and check their types and values.
102 * @param identifier {@link InstanceIdentifierContext}
103 * @param uriInfo URI info
104 * @return {@link WriterParameters}
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();
113 // check only allowed parameters
114 final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
115 checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
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());
125 final List<String> fields = queryParams.getOrDefault(RestconfDataServiceConstant.ReadData.FIELDS, List.of());
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);
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);
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)"));
149 // check and set depth
150 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
151 final Integer value = Ints.tryParse(depth.get(0));
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\""));
160 builder.setDepth(value);
164 // check and set fields
165 if (!fields.isEmpty()) {
166 if (identifier.getMountPoint() != null) {
167 builder.setFieldPaths(parseFieldsPaths(identifier, fields.get(0)));
169 builder.setFields(parseFieldsParameter(identifier, fields.get(0)));
173 // check and set withDefaults parameter
174 if (!withDefaults.isEmpty()) {
175 final String str = withDefaults.get(0);
176 final WithDefaults val = WithDefaults.forValue(str);
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()));
186 case REPORT_ALL_TAGGED:
187 builder.setTagged(true);
190 builder.setWithDefault(val.value());
193 return builder.build();
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.
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}
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);
216 return prepareDataByParamWithDef(
217 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
218 path, withDefa, ctx);
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);
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)"));
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.
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}
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);
253 return prepareDataByParamWithDef(
254 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields),
255 path, withDefa, ctx);
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);
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)"));
269 * Check if URI does not contain value for the same parameter more than once.
271 * @param parameterValues URI parameter values
272 * @param parameterName URI parameter name
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);
284 * Check if URI does not contain not allowed parameters for specified operation.
286 * @param usedParameters parameters used in URI request
287 * @param allowedParameters allowed parameters for operation
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);
302 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
303 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
313 throw new RestconfDocumentedException("");
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();
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();
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());
360 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
361 leafBuilder.withValue(((LeafNode<?>) child).body());
362 builder.withChild(leafBuilder.build());
365 if (defaultVal != null && defaultVal.equals(nodeVal)) {
366 leafBuilder.withValue(((LeafNode<?>) child).body());
367 builder.withChild(leafBuilder.build());
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());
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);
412 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
413 leafBuilder.withValue(((LeafNode<?>) child).body());
414 builder.withChild(leafBuilder.build());
417 if (defaultVal != null && defaultVal.equals(nodeVal)) {
418 leafBuilder.withValue(((LeafNode<?>) child).body());
419 builder.withChild(leafBuilder.build());
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)
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}
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);
443 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
444 * specified subtrees that should only be read.
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}
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);
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);
469 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory);
471 return dataFactory.build();
475 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
476 * {@link RestconfStrategy} provided as a parameter if any.
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}
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,
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);
496 configDataNode = prepareDataByParamWithDef(
497 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
498 path, withDefa, ctx);
501 return mergeConfigAndSTateDataIfNeeded(stateDataNode, configDataNode);
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.
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}
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,
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);
528 configDataNode = prepareDataByParamWithDef(
529 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields),
530 path, withDefa, ctx);
533 return mergeConfigAndSTateDataIfNeeded(stateDataNode, configDataNode);
536 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
537 final NormalizedNode configDataNode) {
539 if (stateDataNode == null && configDataNode == null) {
543 // return config data
544 if (stateDataNode == null) {
545 return configDataNode;
549 if (configDataNode == null) {
550 return stateDataNode;
553 // merge data from config and state
554 return mergeStateAndConfigData(stateDataNode, configDataNode);
558 * Merge state and config data into a single NormalizedNode.
560 * @param stateDataNode data node of state data
561 * @param configDataNode data node of config data
562 * @return {@link NormalizedNode}
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);
570 return prepareData(configDataNode, stateDataNode);
575 * Validates whether the two NormalizedNodes can be merged.
577 * @param stateDataNode data node of state data
578 * @param configDataNode data node of config data
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.");
590 * Prepare and map data for rpc.
592 * @param configDataNode data node of config data
593 * @param stateDataNode data node of state data
594 * @return {@link NormalizedNode}
596 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
597 final @NonNull NormalizedNode stateDataNode) {
598 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
600 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
603 mapRpcDataNode(configDataNode, mapEntryBuilder);
605 mapRpcDataNode(stateDataNode, mapEntryBuilder);
607 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
608 .addChild(mapEntryBuilder.build())
613 * Map node to map entry builder.
615 * @param dataNode data node
616 * @param mapEntryBuilder builder for mapping data
618 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
619 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
620 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
624 * Prepare and map all data from DS.
626 * @param configDataNode data node of config data
627 * @param stateDataNode data node of state data
628 * @return {@link NormalizedNode}
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());
638 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
640 return builder.build();
641 } else if (configDataNode instanceof MapNode) {
642 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
643 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
646 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
648 return builder.build();
649 } else if (configDataNode instanceof MapEntryNode) {
650 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
651 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
654 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
656 return builder.build();
657 } else if (configDataNode instanceof ContainerNode) {
658 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
659 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
662 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
664 return builder.build();
665 } else if (configDataNode instanceof AugmentationNode) {
666 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
667 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
669 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
670 ((AugmentationNode) stateDataNode).body(), builder);
672 return builder.build();
673 } else if (configDataNode instanceof ChoiceNode) {
674 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
675 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
678 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
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());
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());
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())
702 } else if (configDataNode instanceof UnkeyedListNode) {
703 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
704 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
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());
713 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
714 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
715 return builder.build();
717 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
722 * Map value from container node to builder.
724 * @param configData collection of config data nodes
725 * @param stateData collection of state data nodes
726 * @param builder builder
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()));
736 // merge config and state data of children with different identifiers
737 mapDataToBuilder(configMap, stateMap, builder);
739 // merge config and state data of children with the same identifiers
740 mergeDataToBuilder(configMap, stateMap, builder);
744 * Map data with different identifiers to builder. Data with different identifiers can be just added
745 * as childs to parent node.
747 * @param configMap map of config data nodes
748 * @param stateMap map of state data nodes
749 * @param builder - builder
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()));
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.
764 * @param configMap immutable config data
765 * @param stateMap immutable state data
766 * @param builder - builder
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()))));