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.Arrays;
17 import java.util.Collection;
18 import java.util.List;
20 import java.util.Optional;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24 import javax.ws.rs.core.MultivaluedMap;
25 import javax.ws.rs.core.UriInfo;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
29 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.errors.RestconfError;
33 import org.opendaylight.restconf.nb.rfc8040.ContentParameter;
34 import org.opendaylight.restconf.nb.rfc8040.DepthParameter;
35 import org.opendaylight.restconf.nb.rfc8040.FieldsParameter;
36 import org.opendaylight.restconf.nb.rfc8040.WithDefaultsParameter;
37 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
38 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
39 import org.opendaylight.yangtools.yang.common.ErrorTag;
40 import org.opendaylight.yangtools.yang.common.ErrorType;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
72 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
73 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
76 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
81 * Util class for read data from data store via transaction.
85 * <li>all (config + state)
88 public final class ReadDataTransactionUtil {
90 // FIXME: these are known to DepthParameter
91 private static final String UNBOUNDED = "unbounded";
92 private static final int MIN_DEPTH = 1;
93 private static final int MAX_DEPTH = 65535;
95 private static final Set<String> ALLOWED_PARAMETERS = Set.of(
96 ContentParameter.uriName(),
97 DepthParameter.uriName(),
98 FieldsParameter.uriName(),
99 WithDefaultsParameter.uriName());
100 private static final List<String> DEFAULT_CONTENT = List.of(ContentParameter.ALL.uriValue());
101 private static final List<String> DEFAULT_DEPTH = List.of(UNBOUNDED);
102 private static final List<String> POSSIBLE_CONTENT = Arrays.stream(ContentParameter.values())
103 .map(ContentParameter::uriValue)
104 .collect(Collectors.toUnmodifiableList());
105 private static final List<String> POSSIBLE_WITH_DEFAULTS = Arrays.stream(WithDefaultsParameter.values())
106 .map(WithDefaultsParameter::uriValue)
107 .collect(Collectors.toUnmodifiableList());
109 private static final String READ_TYPE_TX = "READ";
111 private ReadDataTransactionUtil() {
116 * Parse parameters from URI request and check their types and values.
118 * @param identifier {@link InstanceIdentifierContext}
119 * @param uriInfo URI info
120 * @return {@link QueryParameters}
122 public static QueryParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
123 final UriInfo uriInfo) {
124 final QueryParameters.Builder builder = QueryParameters.builder();
125 if (uriInfo == null) {
126 return builder.build();
129 // check only allowed parameters
130 final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
131 checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
133 // read parameters from URI or set default values
134 final List<String> content = queryParams.getOrDefault(ContentParameter.uriName(), DEFAULT_CONTENT);
135 final List<String> depth = queryParams.getOrDefault(DepthParameter.uriName(), DEFAULT_DEPTH);
136 final List<String> withDefaults = queryParams.getOrDefault(WithDefaultsParameter.uriName(), List.of());
138 final List<String> fields = queryParams.getOrDefault(FieldsParameter.uriName(), List.of());
140 // parameter can be in URI at most once
141 checkParameterCount(content, ContentParameter.uriName());
142 checkParameterCount(depth, DepthParameter.uriName());
143 checkParameterCount(fields, FieldsParameter.uriName());
144 checkParameterCount(withDefaults, WithDefaultsParameter.uriName());
146 // check and set content
147 final String contentValueStr = content.get(0);
148 builder.setContent(RestconfDocumentedException.throwIfNull(
149 ContentParameter.forUriValue(contentValueStr), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
150 "Invalid content parameter: %s, allowed values are %s", contentValueStr, POSSIBLE_CONTENT));
152 // check and set depth
153 if (!depth.get(0).equals(UNBOUNDED)) {
154 final Integer value = Ints.tryParse(depth.get(0));
156 if (value == null || value < MIN_DEPTH || value > MAX_DEPTH) {
157 throw new RestconfDocumentedException(
158 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
159 "Invalid depth parameter: " + depth, null,
160 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
162 builder.setDepth(value);
166 // check and set fields
167 if (!fields.isEmpty()) {
168 if (identifier.getMountPoint() != null) {
169 builder.setFieldPaths(parseFieldsPaths(identifier, fields.get(0)));
171 builder.setFields(parseFieldsParameter(identifier, fields.get(0)));
175 // check and set withDefaults parameter
176 if (!withDefaults.isEmpty()) {
177 final String str = withDefaults.get(0);
178 final WithDefaultsParameter val = WithDefaultsParameter.forUriValue(str);
180 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
181 "Invalid with-defaults parameter: " + str, null,
182 "The with-defaults parameter must be a string in " + POSSIBLE_WITH_DEFAULTS));
188 case REPORT_ALL_TAGGED:
189 builder.setTagged(true);
192 builder.setWithDefault(val);
195 return builder.build();
199 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
200 * inside of object {@link RestconfStrategy} provided as a parameter.
202 * @param content type of data to read (config, state, all)
203 * @param path the path to read
204 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
205 * @param withDefa value of with-defaults parameter
206 * @param ctx schema context
207 * @return {@link NormalizedNode}
209 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
210 final @NonNull YangInstanceIdentifier path,
211 final @NonNull RestconfStrategy strategy,
212 final WithDefaultsParameter withDefa,
213 final EffectiveModelContext ctx) {
214 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
217 return readAllData(strategy, path, withDefa, ctx);
219 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
220 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
222 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
224 throw new RestconfDocumentedException(
225 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
226 "Invalid content parameter: " + content.uriValue(), null,
227 "The content parameter value must be either config, nonconfig or all (default)"));
232 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
233 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
235 * @param content type of data to read (config, state, all)
236 * @param path the parent path to read
237 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
238 * @param withDefa value of with-defaults parameter
239 * @param ctx schema context
240 * @param fields paths to selected subtrees which should be read, relative to to the parent path
241 * @return {@link NormalizedNode}
243 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
244 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
245 final @Nullable WithDefaultsParameter withDefa, @NonNull final EffectiveModelContext ctx,
246 final @NonNull List<YangInstanceIdentifier> fields) {
247 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
250 return readAllData(strategy, path, withDefa, ctx, fields);
252 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
254 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
256 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
258 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
259 "Invalid content parameter: " + content.uriValue(), null,
260 "The content parameter value must be either config, nonconfig or all (default)"));
265 * Check if URI does not contain value for the same parameter more than once.
267 * @param parameterValues URI parameter values
268 * @param parameterName URI parameter name
271 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
272 if (parameterValues.size() > 1) {
273 throw new RestconfDocumentedException(
274 "Parameter " + parameterName + " can appear at most once in request URI",
275 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
280 * Check if URI does not contain not allowed parameters for specified operation.
282 * @param usedParameters parameters used in URI request
283 * @param allowedParameters allowed parameters for operation
286 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
287 final @NonNull Set<String> allowedParameters) {
288 if (!allowedParameters.containsAll(usedParameters)) {
289 final Set<String> notAllowedParameters = usedParameters.stream()
290 .filter(param -> !allowedParameters.contains(param))
291 .collect(Collectors.toSet());
292 throw new RestconfDocumentedException(
293 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
294 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
298 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
299 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
309 throw new RestconfDocumentedException("Unsupported with-defaults value " + withDefa.uriValue());
312 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
313 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
314 if (result instanceof ContainerNode) {
315 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
316 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
317 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
318 return builder.build();
320 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
321 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
322 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
323 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
324 return builder.build();
328 private static void buildMapEntryBuilder(
329 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
330 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
331 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
332 for (final DataContainerChild child : result.body()) {
333 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
334 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
335 if (child instanceof ContainerNode) {
336 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
337 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
338 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
339 builder.withChild(childBuilder.build());
340 } else if (child instanceof MapNode) {
341 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
342 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
343 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
344 ((ListSchemaNode) childSchema).getKeyDefinition());
345 builder.withChild(childBuilder.build());
346 } else if (child instanceof LeafNode) {
347 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
348 final Object nodeVal = child.body();
349 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
350 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
351 if (keys.contains(child.getIdentifier().getNodeType())) {
352 leafBuilder.withValue(((LeafNode<?>) child).body());
353 builder.withChild(leafBuilder.build());
356 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
357 leafBuilder.withValue(((LeafNode<?>) child).body());
358 builder.withChild(leafBuilder.build());
361 if (defaultVal != null && defaultVal.equals(nodeVal)) {
362 leafBuilder.withValue(((LeafNode<?>) child).body());
363 builder.withChild(leafBuilder.build());
371 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
372 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
373 final boolean trim, final List<QName> keys) {
374 for (final MapEntryNode mapEntryNode : result.body()) {
375 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
376 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
377 .getDataSchemaNode();
378 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
379 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
380 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
381 builder.withChild(mapEntryBuilder.build());
385 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
386 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
387 final YangInstanceIdentifier actualPath, final boolean trim) {
388 for (final DataContainerChild child : result.body()) {
389 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
390 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
391 if (child instanceof ContainerNode) {
392 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
393 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
394 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
395 builder.withChild(builderChild.build());
396 } else if (child instanceof MapNode) {
397 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
398 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
399 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
400 ((ListSchemaNode) childSchema).getKeyDefinition());
401 builder.withChild(childBuilder.build());
402 } else if (child instanceof LeafNode) {
403 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
404 final Object nodeVal = child.body();
405 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
406 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
408 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
409 leafBuilder.withValue(((LeafNode<?>) child).body());
410 builder.withChild(leafBuilder.build());
413 if (defaultVal != null && defaultVal.equals(nodeVal)) {
414 leafBuilder.withValue(((LeafNode<?>) child).body());
415 builder.withChild(leafBuilder.build());
423 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
424 * If don't, we have to read all data from DS (state + config)
426 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
427 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
428 * in {@link RestconfStrategy} if any
429 * @return {@link NormalizedNode}
431 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
432 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
433 return extractReadData(strategy, path, strategy.read(store, path));
437 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
438 * specified subtrees that should only be read.
440 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
441 * @param store datastore type
442 * @param path parent path to selected fields
443 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
444 * in {@link RestconfStrategy} if any
445 * @param fields paths to selected subtrees which should be read, relative to to the parent path
446 * @return {@link NormalizedNode}
448 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
449 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
450 final @NonNull List<YangInstanceIdentifier> fields) {
451 return extractReadData(strategy, path, strategy.read(store, path, fields));
454 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
455 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
456 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
457 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
458 return dataFactory.build();
462 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
463 * {@link RestconfStrategy} provided as a parameter if any.
465 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
466 * @param withDefa with-defaults parameter
467 * @param ctx schema context
468 * @return {@link NormalizedNode}
470 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
471 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
472 // PREPARE STATE DATA NODE
473 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
474 // PREPARE CONFIG DATA NODE
475 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
478 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
479 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
483 * Read config and state data with selected subtrees that should only be read, then map them.
484 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
486 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
487 * @param path parent path to selected fields
488 * @param withDefa with-defaults parameter
489 * @param ctx schema context
490 * @param fields paths to selected subtrees which should be read, relative to to the parent path
491 * @return {@link NormalizedNode}
493 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
494 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParameter withDefa,
495 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
496 // PREPARE STATE DATA NODE
497 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
500 // PREPARE CONFIG DATA NODE
501 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
503 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
504 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
507 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
508 final NormalizedNode configDataNode) {
510 if (stateDataNode == null && configDataNode == null) {
514 // return config data
515 if (stateDataNode == null) {
516 return configDataNode;
520 if (configDataNode == null) {
521 return stateDataNode;
524 // merge data from config and state
525 return mergeStateAndConfigData(stateDataNode, configDataNode);
529 * Merge state and config data into a single NormalizedNode.
531 * @param stateDataNode data node of state data
532 * @param configDataNode data node of config data
533 * @return {@link NormalizedNode}
535 private static @NonNull NormalizedNode mergeStateAndConfigData(
536 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
537 validateNodeMerge(stateDataNode, configDataNode);
538 if (configDataNode instanceof RpcDefinition) {
539 return prepareRpcData(configDataNode, stateDataNode);
541 return prepareData(configDataNode, stateDataNode);
546 * Validates whether the two NormalizedNodes can be merged.
548 * @param stateDataNode data node of state data
549 * @param configDataNode data node of config data
551 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
552 final @NonNull NormalizedNode configDataNode) {
553 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
554 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
555 if (!moduleOfStateData.equals(moduleOfConfigData)) {
556 throw new RestconfDocumentedException("Unable to merge data from different modules.");
561 * Prepare and map data for rpc.
563 * @param configDataNode data node of config data
564 * @param stateDataNode data node of state data
565 * @return {@link NormalizedNode}
567 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
568 final @NonNull NormalizedNode stateDataNode) {
569 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
571 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
574 mapRpcDataNode(configDataNode, mapEntryBuilder);
576 mapRpcDataNode(stateDataNode, mapEntryBuilder);
578 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
579 .addChild(mapEntryBuilder.build())
584 * Map node to map entry builder.
586 * @param dataNode data node
587 * @param mapEntryBuilder builder for mapping data
589 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
590 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
591 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
595 * Prepare and map all data from DS.
597 * @param configDataNode data node of config data
598 * @param stateDataNode data node of state data
599 * @return {@link NormalizedNode}
601 @SuppressWarnings("unchecked")
602 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
603 final @NonNull NormalizedNode stateDataNode) {
604 if (configDataNode instanceof UserMapNode) {
605 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
606 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
609 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
611 return builder.build();
612 } else if (configDataNode instanceof MapNode) {
613 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
614 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
617 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
619 return builder.build();
620 } else if (configDataNode instanceof MapEntryNode) {
621 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
622 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
625 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
627 return builder.build();
628 } else if (configDataNode instanceof ContainerNode) {
629 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
630 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
633 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
635 return builder.build();
636 } else if (configDataNode instanceof AugmentationNode) {
637 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
638 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
640 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
641 ((AugmentationNode) stateDataNode).body(), builder);
643 return builder.build();
644 } else if (configDataNode instanceof ChoiceNode) {
645 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
646 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
649 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
651 return builder.build();
652 } else if (configDataNode instanceof LeafNode) {
653 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
654 } else if (configDataNode instanceof UserLeafSetNode) {
655 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
656 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
658 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
659 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
660 return builder.build();
661 } else if (configDataNode instanceof LeafSetNode) {
662 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
663 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
665 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
666 ((LeafSetNode<Object>) stateDataNode).body(), builder);
667 return builder.build();
668 } else if (configDataNode instanceof LeafSetEntryNode) {
669 return Builders.leafSetEntryBuilder()
670 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
671 .withValue(configDataNode.body())
673 } else if (configDataNode instanceof UnkeyedListNode) {
674 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
675 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
677 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
678 ((UnkeyedListNode) stateDataNode).body(), builder);
679 return builder.build();
680 } else if (configDataNode instanceof UnkeyedListEntryNode) {
681 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
682 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
684 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
685 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
686 return builder.build();
688 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
693 * Map value from container node to builder.
695 * @param configData collection of config data nodes
696 * @param stateData collection of state data nodes
697 * @param builder builder
699 private static <T extends NormalizedNode> void mapValueToBuilder(
700 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
701 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
702 final Map<PathArgument, T> configMap = configData.stream().collect(
703 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
704 final Map<PathArgument, T> stateMap = stateData.stream().collect(
705 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
707 // merge config and state data of children with different identifiers
708 mapDataToBuilder(configMap, stateMap, builder);
710 // merge config and state data of children with the same identifiers
711 mergeDataToBuilder(configMap, stateMap, builder);
715 * Map data with different identifiers to builder. Data with different identifiers can be just added
716 * as childs to parent node.
718 * @param configMap map of config data nodes
719 * @param stateMap map of state data nodes
720 * @param builder - builder
722 private static <T extends NormalizedNode> void mapDataToBuilder(
723 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
724 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
725 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
726 y -> builder.addChild(y.getValue()));
727 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
728 y -> builder.addChild(y.getValue()));
732 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
733 * go one level down with {@code prepareData} method.
735 * @param configMap immutable config data
736 * @param stateMap immutable state data
737 * @param builder - builder
739 @SuppressWarnings("unchecked")
740 private static <T extends NormalizedNode> void mergeDataToBuilder(
741 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
742 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
743 // it is enough to process only config data because operational contains the same data
744 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
745 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));