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.common.errors.RestconfError.ErrorTag;
35 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
36 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
37 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.ReadData.WithDefaults;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
49 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
67 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
68 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
69 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
70 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
73 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
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 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
136 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
137 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
138 throw new RestconfDocumentedException(
139 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
140 "Invalid content parameter: " + contentValue, null,
141 "The content parameter value must be either config, nonconfig or all (default)"));
145 builder.setContent(content.get(0));
147 // check and set depth
148 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
149 final Integer value = Ints.tryParse(depth.get(0));
151 if (value == null || value < RestconfDataServiceConstant.ReadData.MIN_DEPTH
152 || value > RestconfDataServiceConstant.ReadData.MAX_DEPTH) {
153 throw new RestconfDocumentedException(
154 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
155 "Invalid depth parameter: " + depth, null,
156 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
158 builder.setDepth(value);
162 // check and set fields
163 if (!fields.isEmpty()) {
164 if (identifier.getMountPoint() != null) {
165 builder.setFieldPaths(parseFieldsPaths(identifier, fields.get(0)));
167 builder.setFields(parseFieldsParameter(identifier, fields.get(0)));
171 // check and set withDefaults parameter
172 if (!withDefaults.isEmpty()) {
173 final String str = withDefaults.get(0);
174 final WithDefaults val = WithDefaults.forValue(str);
176 throw new RestconfDocumentedException(new RestconfError(RestconfError.ErrorType.PROTOCOL,
177 RestconfError.ErrorTag.INVALID_VALUE, "Invalid with-defaults parameter: " + str, null,
178 "The with-defaults parameter must be a string in " + WithDefaults.possibleValues()));
184 case REPORT_ALL_TAGGED:
185 builder.setTagged(true);
188 builder.setWithDefault(val.value());
191 return builder.build();
195 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
196 * inside of object {@link RestconfStrategy} provided as a parameter.
198 * @param valueOfContent type of data to read (config, state, all)
199 * @param path the path to read
200 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
201 * @param withDefa value of with-defaults parameter
202 * @param ctx schema context
203 * @return {@link NormalizedNode}
205 public static @Nullable NormalizedNode readData(final @NonNull String valueOfContent,
206 final @NonNull YangInstanceIdentifier path,
207 final @NonNull RestconfStrategy strategy,
208 final String withDefa, final EffectiveModelContext ctx) {
209 switch (valueOfContent) {
210 case RestconfDataServiceConstant.ReadData.CONFIG:
211 if (withDefa == null) {
212 return readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true);
214 return prepareDataByParamWithDef(
215 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
216 path, withDefa, ctx);
218 case RestconfDataServiceConstant.ReadData.NONCONFIG:
219 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, true);
220 case RestconfDataServiceConstant.ReadData.ALL:
221 return readAllData(strategy, path, withDefa, ctx);
223 throw new RestconfDocumentedException(
224 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
225 "Invalid content parameter: " + valueOfContent, null,
226 "The content parameter value must be either config, nonconfig or all (default)"));
231 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
232 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
234 * @param valueOfContent type of data to read (config, state, all)
235 * @param path the parent path to read
236 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
237 * @param withDefa value of with-defaults parameter
238 * @param ctx schema context
239 * @param fields paths to selected subtrees which should be read, relative to to the parent path
240 * @return {@link NormalizedNode}
242 public static @Nullable NormalizedNode readData(final @NonNull String valueOfContent,
243 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
244 final @Nullable String withDefa, @NonNull final EffectiveModelContext ctx,
245 final @NonNull List<YangInstanceIdentifier> fields) {
246 switch (valueOfContent) {
247 case RestconfDataServiceConstant.ReadData.CONFIG:
248 if (withDefa == null) {
249 return readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields);
251 return prepareDataByParamWithDef(
252 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields),
253 path, withDefa, ctx);
255 case RestconfDataServiceConstant.ReadData.NONCONFIG:
256 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, true, fields);
257 case RestconfDataServiceConstant.ReadData.ALL:
258 return readAllData(strategy, path, withDefa, ctx, fields);
260 throw new RestconfDocumentedException(new RestconfError(RestconfError.ErrorType.PROTOCOL,
261 RestconfError.ErrorTag.INVALID_VALUE, "Invalid content parameter: " + valueOfContent, null,
262 "The content parameter value must be either config, nonconfig or all (default)"));
267 * Check if URI does not contain value for the same parameter more than once.
269 * @param parameterValues URI parameter values
270 * @param parameterName URI parameter name
273 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
274 if (parameterValues.size() > 1) {
275 throw new RestconfDocumentedException(
276 "Parameter " + parameterName + " can appear at most once in request URI",
277 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
282 * Check if URI does not contain not allowed parameters for specified operation.
284 * @param usedParameters parameters used in URI request
285 * @param allowedParameters allowed parameters for operation
288 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
289 final @NonNull Set<String> allowedParameters) {
290 if (!allowedParameters.containsAll(usedParameters)) {
291 final Set<String> notAllowedParameters = usedParameters.stream()
292 .filter(param -> !allowedParameters.contains(param))
293 .collect(Collectors.toSet());
294 throw new RestconfDocumentedException(
295 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
296 RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE);
300 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
301 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
311 throw new RestconfDocumentedException("");
314 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
315 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
316 if (result instanceof ContainerNode) {
317 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
318 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
319 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
320 return builder.build();
322 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
323 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
324 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
325 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
326 return builder.build();
330 private static void buildMapEntryBuilder(
331 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
332 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
333 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
334 for (final DataContainerChild child : result.body()) {
335 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
336 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
337 if (child instanceof ContainerNode) {
338 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
339 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
340 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
341 builder.withChild(childBuilder.build());
342 } else if (child instanceof MapNode) {
343 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
344 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
345 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
346 ((ListSchemaNode) childSchema).getKeyDefinition());
347 builder.withChild(childBuilder.build());
348 } else if (child instanceof LeafNode) {
349 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
350 final Object nodeVal = child.body();
351 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
352 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
353 if (keys.contains(child.getIdentifier().getNodeType())) {
354 leafBuilder.withValue(((LeafNode<?>) child).body());
355 builder.withChild(leafBuilder.build());
358 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
359 leafBuilder.withValue(((LeafNode<?>) child).body());
360 builder.withChild(leafBuilder.build());
363 if (defaultVal != null && defaultVal.equals(nodeVal)) {
364 leafBuilder.withValue(((LeafNode<?>) child).body());
365 builder.withChild(leafBuilder.build());
373 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
374 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
375 final boolean trim, final List<QName> keys) {
376 for (final MapEntryNode mapEntryNode : result.body()) {
377 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
378 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
379 .getDataSchemaNode();
380 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
381 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
382 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
383 builder.withChild(mapEntryBuilder.build());
387 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
388 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
389 final YangInstanceIdentifier actualPath, final boolean trim) {
390 for (final DataContainerChild child : result.body()) {
391 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
392 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
393 if (child instanceof ContainerNode) {
394 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
395 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
396 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
397 builder.withChild(builderChild.build());
398 } else if (child instanceof MapNode) {
399 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
400 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
401 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
402 ((ListSchemaNode) childSchema).getKeyDefinition());
403 builder.withChild(childBuilder.build());
404 } else if (child instanceof LeafNode) {
405 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
406 final Object nodeVal = child.body();
407 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
408 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
410 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
411 leafBuilder.withValue(((LeafNode<?>) child).body());
412 builder.withChild(leafBuilder.build());
415 if (defaultVal != null && defaultVal.equals(nodeVal)) {
416 leafBuilder.withValue(((LeafNode<?>) child).body());
417 builder.withChild(leafBuilder.build());
425 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
426 * If don't, we have to read all data from DS (state + config)
428 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
429 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
430 * in {@link RestconfStrategy} if any
431 * @return {@link NormalizedNode}
433 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
434 final LogicalDatastoreType store, final YangInstanceIdentifier path,
435 final boolean closeTransactionChain) {
436 final ListenableFuture<Optional<NormalizedNode>> listenableFuture = strategy.read(store, path);
437 return extractReadData(strategy, path, closeTransactionChain, listenableFuture);
441 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
442 * specified subtrees that should only be read.
444 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
445 * @param store datastore type
446 * @param path parent path to selected fields
447 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
448 * in {@link RestconfStrategy} if any
449 * @param fields paths to selected subtrees which should be read, relative to to the parent path
450 * @return {@link NormalizedNode}
452 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
453 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
454 final boolean closeTransactionChain, final @NonNull List<YangInstanceIdentifier> fields) {
455 final ListenableFuture<Optional<NormalizedNode>> listenableFuture = strategy.read(store, path, fields);
456 return extractReadData(strategy, path, closeTransactionChain, listenableFuture);
459 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
460 final YangInstanceIdentifier path, final boolean closeTransactionChain,
461 final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
462 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
463 if (closeTransactionChain) {
464 //Method close transactionChain if any
465 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, strategy, path);
467 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory);
469 return dataFactory.build();
473 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
474 * {@link RestconfStrategy} provided as a parameter if any.
476 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
477 * @param withDefa with-defaults parameter
478 * @param ctx schema context
479 * @return {@link NormalizedNode}
481 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
482 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
483 // PREPARE STATE DATA NODE
484 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
487 // PREPARE CONFIG DATA NODE
488 final NormalizedNode configDataNode;
489 //Here will be closed transactionChain if any
490 if (withDefa == null) {
491 configDataNode = readDataViaTransaction(
492 strategy, LogicalDatastoreType.CONFIGURATION, path, true);
494 configDataNode = prepareDataByParamWithDef(
495 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
496 path, withDefa, ctx);
499 return mergeConfigAndSTateDataIfNeeded(stateDataNode, configDataNode);
503 * Read config and state data with selected subtrees that should only be read, then map them.
504 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
506 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
507 * @param path parent path to selected fields
508 * @param withDefa with-defaults parameter
509 * @param ctx schema context
510 * @param fields paths to selected subtrees which should be read, relative to to the parent path
511 * @return {@link NormalizedNode}
513 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
514 final @NonNull YangInstanceIdentifier path, final @Nullable String withDefa,
515 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
516 // PREPARE STATE DATA NODE
517 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
520 // PREPARE CONFIG DATA NODE
521 final NormalizedNode configDataNode;
522 //Here will be closed transactionChain if any
523 if (withDefa == null) {
524 configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields);
526 configDataNode = prepareDataByParamWithDef(
527 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true, fields),
528 path, withDefa, ctx);
531 return mergeConfigAndSTateDataIfNeeded(stateDataNode, configDataNode);
534 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
535 final NormalizedNode configDataNode) {
537 if (stateDataNode == null && configDataNode == null) {
541 // return config data
542 if (stateDataNode == null) {
543 return configDataNode;
547 if (configDataNode == null) {
548 return stateDataNode;
551 // merge data from config and state
552 return mergeStateAndConfigData(stateDataNode, configDataNode);
556 * Merge state and config data into a single NormalizedNode.
558 * @param stateDataNode data node of state data
559 * @param configDataNode data node of config data
560 * @return {@link NormalizedNode}
562 private static @NonNull NormalizedNode mergeStateAndConfigData(
563 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
564 validateNodeMerge(stateDataNode, configDataNode);
565 if (configDataNode instanceof RpcDefinition) {
566 return prepareRpcData(configDataNode, stateDataNode);
568 return prepareData(configDataNode, stateDataNode);
573 * Validates whether the two NormalizedNodes can be merged.
575 * @param stateDataNode data node of state data
576 * @param configDataNode data node of config data
578 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
579 final @NonNull NormalizedNode configDataNode) {
580 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
581 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
582 if (!moduleOfStateData.equals(moduleOfConfigData)) {
583 throw new RestconfDocumentedException("Unable to merge data from different modules.");
588 * Prepare and map data for rpc.
590 * @param configDataNode data node of config data
591 * @param stateDataNode data node of state data
592 * @return {@link NormalizedNode}
594 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
595 final @NonNull NormalizedNode stateDataNode) {
596 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
598 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
601 mapRpcDataNode(configDataNode, mapEntryBuilder);
603 mapRpcDataNode(stateDataNode, mapEntryBuilder);
605 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
606 .addChild(mapEntryBuilder.build())
611 * Map node to map entry builder.
613 * @param dataNode data node
614 * @param mapEntryBuilder builder for mapping data
616 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
617 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
618 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
622 * Prepare and map all data from DS.
624 * @param configDataNode data node of config data
625 * @param stateDataNode data node of state data
626 * @return {@link NormalizedNode}
628 @SuppressWarnings("unchecked")
629 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
630 final @NonNull NormalizedNode stateDataNode) {
631 if (configDataNode instanceof UserMapNode) {
632 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
633 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
636 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
638 return builder.build();
639 } else if (configDataNode instanceof MapNode) {
640 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
641 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
644 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
646 return builder.build();
647 } else if (configDataNode instanceof MapEntryNode) {
648 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
649 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
652 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
654 return builder.build();
655 } else if (configDataNode instanceof ContainerNode) {
656 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
657 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
660 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
662 return builder.build();
663 } else if (configDataNode instanceof AugmentationNode) {
664 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
665 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
667 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
668 ((AugmentationNode) stateDataNode).body(), builder);
670 return builder.build();
671 } else if (configDataNode instanceof ChoiceNode) {
672 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
673 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
676 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
678 return builder.build();
679 } else if (configDataNode instanceof LeafNode) {
680 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
681 } else if (configDataNode instanceof UserLeafSetNode) {
682 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
683 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
685 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
686 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
687 return builder.build();
688 } else if (configDataNode instanceof LeafSetNode) {
689 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
690 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
692 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
693 ((LeafSetNode<Object>) stateDataNode).body(), builder);
694 return builder.build();
695 } else if (configDataNode instanceof LeafSetEntryNode) {
696 return Builders.leafSetEntryBuilder()
697 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
698 .withValue(configDataNode.body())
700 } else if (configDataNode instanceof UnkeyedListNode) {
701 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
702 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
704 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
705 ((UnkeyedListNode) stateDataNode).body(), builder);
706 return builder.build();
707 } else if (configDataNode instanceof UnkeyedListEntryNode) {
708 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
709 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
711 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
712 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
713 return builder.build();
715 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
720 * Map value from container node to builder.
722 * @param configData collection of config data nodes
723 * @param stateData collection of state data nodes
724 * @param builder builder
726 private static <T extends NormalizedNode> void mapValueToBuilder(
727 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
728 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
729 final Map<PathArgument, T> configMap = configData.stream().collect(
730 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
731 final Map<PathArgument, T> stateMap = stateData.stream().collect(
732 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
734 // merge config and state data of children with different identifiers
735 mapDataToBuilder(configMap, stateMap, builder);
737 // merge config and state data of children with the same identifiers
738 mergeDataToBuilder(configMap, stateMap, builder);
742 * Map data with different identifiers to builder. Data with different identifiers can be just added
743 * as childs to parent node.
745 * @param configMap map of config data nodes
746 * @param stateMap map of state data nodes
747 * @param builder - builder
749 private static <T extends NormalizedNode> void mapDataToBuilder(
750 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
751 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
752 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
753 y -> builder.addChild(y.getValue()));
754 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
755 y -> builder.addChild(y.getValue()));
759 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
760 * go one level down with {@code prepareData} method.
762 * @param configMap immutable config data
763 * @param stateMap immutable state data
764 * @param builder - builder
766 @SuppressWarnings("unchecked")
767 private static <T extends NormalizedNode> void mergeDataToBuilder(
768 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
769 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
770 // it is enough to process only config data because operational contains the same data
771 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
772 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));