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.util.concurrent.ListenableFuture;
15 import java.util.Arrays;
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.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError;
32 import org.opendaylight.restconf.nb.rfc8040.ContentParameter;
33 import org.opendaylight.restconf.nb.rfc8040.DepthParameter;
34 import org.opendaylight.restconf.nb.rfc8040.FieldsParameter;
35 import org.opendaylight.restconf.nb.rfc8040.WithDefaultsParameter;
36 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
37 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
38 import org.opendaylight.yangtools.yang.common.ErrorTag;
39 import org.opendaylight.yangtools.yang.common.ErrorType;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.QNameModule;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
70 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
71 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
72 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
75 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
80 * Util class for read data from data store via transaction.
84 * <li>all (config + state)
87 public final class ReadDataTransactionUtil {
88 private static final Set<String> ALLOWED_PARAMETERS = Set.of(
89 ContentParameter.uriName(),
90 DepthParameter.uriName(),
91 FieldsParameter.uriName(),
92 WithDefaultsParameter.uriName());
93 private static final List<String> DEFAULT_CONTENT = List.of(ContentParameter.ALL.uriValue());
94 private static final List<String> DEFAULT_DEPTH = List.of(DepthParameter.unboundedUriValue());
95 private static final List<String> POSSIBLE_CONTENT = Arrays.stream(ContentParameter.values())
96 .map(ContentParameter::uriValue)
97 .collect(Collectors.toUnmodifiableList());
98 private static final List<String> POSSIBLE_WITH_DEFAULTS = Arrays.stream(WithDefaultsParameter.values())
99 .map(WithDefaultsParameter::uriValue)
100 .collect(Collectors.toUnmodifiableList());
102 private static final String READ_TYPE_TX = "READ";
104 private ReadDataTransactionUtil() {
109 * Parse parameters from URI request and check their types and values.
111 * @param identifier {@link InstanceIdentifierContext}
112 * @param uriInfo URI info
113 * @return {@link QueryParameters}
115 public static QueryParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
116 final UriInfo uriInfo) {
117 final QueryParameters.Builder builder = QueryParameters.builder();
118 if (uriInfo == null) {
119 return builder.build();
122 // check only allowed parameters
123 final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
124 checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
126 // read parameters from URI or set default values
127 final List<String> content = queryParams.getOrDefault(ContentParameter.uriName(), DEFAULT_CONTENT);
128 final List<String> depth = queryParams.getOrDefault(DepthParameter.uriName(), DEFAULT_DEPTH);
129 final List<String> withDefaults = queryParams.getOrDefault(WithDefaultsParameter.uriName(), List.of());
131 final List<String> fields = queryParams.getOrDefault(FieldsParameter.uriName(), List.of());
133 // parameter can be in URI at most once
134 checkParameterCount(content, ContentParameter.uriName());
135 checkParameterCount(depth, DepthParameter.uriName());
136 checkParameterCount(fields, FieldsParameter.uriName());
137 checkParameterCount(withDefaults, WithDefaultsParameter.uriName());
139 // check and set content
140 final String contentStr = content.get(0);
141 builder.setContent(RestconfDocumentedException.throwIfNull(
142 ContentParameter.forUriValue(contentStr), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
143 "Invalid content parameter: %s, allowed values are %s", contentStr, POSSIBLE_CONTENT));
145 final String depthStr = depth.get(0);
147 builder.setDepth(DepthParameter.forUriValue(depthStr));
148 } catch (IllegalArgumentException e) {
149 throw new RestconfDocumentedException(e, new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
150 "Invalid depth parameter: " + depthStr, null,
151 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
154 // check and set fields
155 if (!fields.isEmpty()) {
156 if (identifier.getMountPoint() != null) {
157 builder.setFieldPaths(parseFieldsPaths(identifier, fields.get(0)));
159 builder.setFields(parseFieldsParameter(identifier, fields.get(0)));
163 // check and set withDefaults parameter
164 if (!withDefaults.isEmpty()) {
165 final String str = withDefaults.get(0);
166 final WithDefaultsParameter val = WithDefaultsParameter.forUriValue(str);
168 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
169 "Invalid with-defaults parameter: " + str, null,
170 "The with-defaults parameter must be a string in " + POSSIBLE_WITH_DEFAULTS));
176 case REPORT_ALL_TAGGED:
177 builder.setTagged(true);
180 builder.setWithDefault(val);
183 return builder.build();
187 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
188 * inside of object {@link RestconfStrategy} provided as a parameter.
190 * @param content type of data to read (config, state, all)
191 * @param path the path to read
192 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
193 * @param withDefa value of with-defaults parameter
194 * @param ctx schema context
195 * @return {@link NormalizedNode}
197 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
198 final @NonNull YangInstanceIdentifier path,
199 final @NonNull RestconfStrategy strategy,
200 final WithDefaultsParameter withDefa,
201 final EffectiveModelContext ctx) {
202 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
205 return readAllData(strategy, path, withDefa, ctx);
207 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
208 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
210 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
212 throw new RestconfDocumentedException(
213 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
214 "Invalid content parameter: " + content.uriValue(), null,
215 "The content parameter value must be either config, nonconfig or all (default)"));
220 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
221 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
223 * @param content type of data to read (config, state, all)
224 * @param path the parent path to read
225 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
226 * @param withDefa value of with-defaults parameter
227 * @param ctx schema context
228 * @param fields paths to selected subtrees which should be read, relative to to the parent path
229 * @return {@link NormalizedNode}
231 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
232 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
233 final @Nullable WithDefaultsParameter withDefa, @NonNull final EffectiveModelContext ctx,
234 final @NonNull List<YangInstanceIdentifier> fields) {
235 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
238 return readAllData(strategy, path, withDefa, ctx, fields);
240 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
242 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
244 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
246 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
247 "Invalid content parameter: " + content.uriValue(), null,
248 "The content parameter value must be either config, nonconfig or all (default)"));
253 * Check if URI does not contain value for the same parameter more than once.
255 * @param parameterValues URI parameter values
256 * @param parameterName URI parameter name
259 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
260 if (parameterValues.size() > 1) {
261 throw new RestconfDocumentedException(
262 "Parameter " + parameterName + " can appear at most once in request URI",
263 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
268 * Check if URI does not contain not allowed parameters for specified operation.
270 * @param usedParameters parameters used in URI request
271 * @param allowedParameters allowed parameters for operation
274 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
275 final @NonNull Set<String> allowedParameters) {
276 if (!allowedParameters.containsAll(usedParameters)) {
277 final Set<String> notAllowedParameters = usedParameters.stream()
278 .filter(param -> !allowedParameters.contains(param))
279 .collect(Collectors.toSet());
280 throw new RestconfDocumentedException(
281 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
282 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
286 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
287 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
297 throw new RestconfDocumentedException("Unsupported with-defaults value " + withDefa.uriValue());
300 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
301 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
302 if (result instanceof ContainerNode) {
303 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
304 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
305 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
306 return builder.build();
308 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
309 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
310 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
311 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
312 return builder.build();
316 private static void buildMapEntryBuilder(
317 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
318 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
319 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
320 for (final DataContainerChild child : result.body()) {
321 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
322 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
323 if (child instanceof ContainerNode) {
324 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
325 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
326 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
327 builder.withChild(childBuilder.build());
328 } else if (child instanceof MapNode) {
329 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
330 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
331 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
332 ((ListSchemaNode) childSchema).getKeyDefinition());
333 builder.withChild(childBuilder.build());
334 } else if (child instanceof LeafNode) {
335 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
336 final Object nodeVal = child.body();
337 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
338 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
339 if (keys.contains(child.getIdentifier().getNodeType())) {
340 leafBuilder.withValue(((LeafNode<?>) child).body());
341 builder.withChild(leafBuilder.build());
344 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
345 leafBuilder.withValue(((LeafNode<?>) child).body());
346 builder.withChild(leafBuilder.build());
349 if (defaultVal != null && defaultVal.equals(nodeVal)) {
350 leafBuilder.withValue(((LeafNode<?>) child).body());
351 builder.withChild(leafBuilder.build());
359 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
360 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
361 final boolean trim, final List<QName> keys) {
362 for (final MapEntryNode mapEntryNode : result.body()) {
363 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
364 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
365 .getDataSchemaNode();
366 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
367 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
368 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
369 builder.withChild(mapEntryBuilder.build());
373 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
374 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
375 final YangInstanceIdentifier actualPath, final boolean trim) {
376 for (final DataContainerChild child : result.body()) {
377 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
378 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
379 if (child instanceof ContainerNode) {
380 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
381 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
382 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
383 builder.withChild(builderChild.build());
384 } else if (child instanceof MapNode) {
385 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
386 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
387 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
388 ((ListSchemaNode) childSchema).getKeyDefinition());
389 builder.withChild(childBuilder.build());
390 } else if (child instanceof LeafNode) {
391 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
392 final Object nodeVal = child.body();
393 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
394 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
396 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
397 leafBuilder.withValue(((LeafNode<?>) child).body());
398 builder.withChild(leafBuilder.build());
401 if (defaultVal != null && defaultVal.equals(nodeVal)) {
402 leafBuilder.withValue(((LeafNode<?>) child).body());
403 builder.withChild(leafBuilder.build());
411 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
412 * If don't, we have to read all data from DS (state + config)
414 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
415 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
416 * in {@link RestconfStrategy} if any
417 * @return {@link NormalizedNode}
419 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
420 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
421 return extractReadData(strategy, path, strategy.read(store, path));
425 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
426 * specified subtrees that should only be read.
428 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
429 * @param store datastore type
430 * @param path parent path to selected fields
431 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
432 * in {@link RestconfStrategy} if any
433 * @param fields paths to selected subtrees which should be read, relative to to the parent path
434 * @return {@link NormalizedNode}
436 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
437 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
438 final @NonNull List<YangInstanceIdentifier> fields) {
439 return extractReadData(strategy, path, strategy.read(store, path, fields));
442 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
443 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
444 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
445 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
446 return dataFactory.build();
450 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
451 * {@link RestconfStrategy} provided as a parameter if any.
453 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
454 * @param withDefa with-defaults parameter
455 * @param ctx schema context
456 * @return {@link NormalizedNode}
458 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
459 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
460 // PREPARE STATE DATA NODE
461 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
462 // PREPARE CONFIG DATA NODE
463 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
466 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
467 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
471 * Read config and state data with selected subtrees that should only be read, then map them.
472 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
474 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
475 * @param path parent path to selected fields
476 * @param withDefa with-defaults parameter
477 * @param ctx schema context
478 * @param fields paths to selected subtrees which should be read, relative to to the parent path
479 * @return {@link NormalizedNode}
481 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
482 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParameter withDefa,
483 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
484 // PREPARE STATE DATA NODE
485 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
488 // PREPARE CONFIG DATA NODE
489 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
491 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
492 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
495 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
496 final NormalizedNode configDataNode) {
498 if (stateDataNode == null && configDataNode == null) {
502 // return config data
503 if (stateDataNode == null) {
504 return configDataNode;
508 if (configDataNode == null) {
509 return stateDataNode;
512 // merge data from config and state
513 return mergeStateAndConfigData(stateDataNode, configDataNode);
517 * Merge state and config data into a single NormalizedNode.
519 * @param stateDataNode data node of state data
520 * @param configDataNode data node of config data
521 * @return {@link NormalizedNode}
523 private static @NonNull NormalizedNode mergeStateAndConfigData(
524 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
525 validateNodeMerge(stateDataNode, configDataNode);
526 if (configDataNode instanceof RpcDefinition) {
527 return prepareRpcData(configDataNode, stateDataNode);
529 return prepareData(configDataNode, stateDataNode);
534 * Validates whether the two NormalizedNodes can be merged.
536 * @param stateDataNode data node of state data
537 * @param configDataNode data node of config data
539 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
540 final @NonNull NormalizedNode configDataNode) {
541 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
542 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
543 if (!moduleOfStateData.equals(moduleOfConfigData)) {
544 throw new RestconfDocumentedException("Unable to merge data from different modules.");
549 * Prepare and map data for rpc.
551 * @param configDataNode data node of config data
552 * @param stateDataNode data node of state data
553 * @return {@link NormalizedNode}
555 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
556 final @NonNull NormalizedNode stateDataNode) {
557 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
559 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
562 mapRpcDataNode(configDataNode, mapEntryBuilder);
564 mapRpcDataNode(stateDataNode, mapEntryBuilder);
566 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
567 .addChild(mapEntryBuilder.build())
572 * Map node to map entry builder.
574 * @param dataNode data node
575 * @param mapEntryBuilder builder for mapping data
577 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
578 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
579 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
583 * Prepare and map all data from DS.
585 * @param configDataNode data node of config data
586 * @param stateDataNode data node of state data
587 * @return {@link NormalizedNode}
589 @SuppressWarnings("unchecked")
590 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
591 final @NonNull NormalizedNode stateDataNode) {
592 if (configDataNode instanceof UserMapNode) {
593 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
594 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
597 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
599 return builder.build();
600 } else if (configDataNode instanceof MapNode) {
601 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
602 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
605 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
607 return builder.build();
608 } else if (configDataNode instanceof MapEntryNode) {
609 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
610 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
613 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
615 return builder.build();
616 } else if (configDataNode instanceof ContainerNode) {
617 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
618 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
621 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
623 return builder.build();
624 } else if (configDataNode instanceof AugmentationNode) {
625 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
626 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
628 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
629 ((AugmentationNode) stateDataNode).body(), builder);
631 return builder.build();
632 } else if (configDataNode instanceof ChoiceNode) {
633 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
634 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
637 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
639 return builder.build();
640 } else if (configDataNode instanceof LeafNode) {
641 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
642 } else if (configDataNode instanceof UserLeafSetNode) {
643 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
644 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
646 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
647 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
648 return builder.build();
649 } else if (configDataNode instanceof LeafSetNode) {
650 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
651 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
653 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
654 ((LeafSetNode<Object>) stateDataNode).body(), builder);
655 return builder.build();
656 } else if (configDataNode instanceof LeafSetEntryNode) {
657 return Builders.leafSetEntryBuilder()
658 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
659 .withValue(configDataNode.body())
661 } else if (configDataNode instanceof UnkeyedListNode) {
662 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
663 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
665 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
666 ((UnkeyedListNode) stateDataNode).body(), builder);
667 return builder.build();
668 } else if (configDataNode instanceof UnkeyedListEntryNode) {
669 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
670 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
672 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
673 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
674 return builder.build();
676 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
681 * Map value from container node to builder.
683 * @param configData collection of config data nodes
684 * @param stateData collection of state data nodes
685 * @param builder builder
687 private static <T extends NormalizedNode> void mapValueToBuilder(
688 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
689 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
690 final Map<PathArgument, T> configMap = configData.stream().collect(
691 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
692 final Map<PathArgument, T> stateMap = stateData.stream().collect(
693 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
695 // merge config and state data of children with different identifiers
696 mapDataToBuilder(configMap, stateMap, builder);
698 // merge config and state data of children with the same identifiers
699 mergeDataToBuilder(configMap, stateMap, builder);
703 * Map data with different identifiers to builder. Data with different identifiers can be just added
704 * as childs to parent node.
706 * @param configMap map of config data nodes
707 * @param stateMap map of state data nodes
708 * @param builder - builder
710 private static <T extends NormalizedNode> void mapDataToBuilder(
711 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
712 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
713 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
714 y -> builder.addChild(y.getValue()));
715 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
716 y -> builder.addChild(y.getValue()));
720 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
721 * go one level down with {@code prepareData} method.
723 * @param configMap immutable config data
724 * @param stateMap immutable state data
725 * @param builder - builder
727 @SuppressWarnings("unchecked")
728 private static <T extends NormalizedNode> void mergeDataToBuilder(
729 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
730 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
731 // it is enough to process only config data because operational contains the same data
732 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
733 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));