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 com.google.common.base.Verify.verifyNotNull;
11 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsParameter;
12 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsPaths;
14 import com.google.common.annotations.VisibleForTesting;
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 {
89 private static final Set<String> ALLOWED_PARAMETERS = Set.of(ContentParameter.uriName(), DepthParameter.uriName(),
90 FieldsParameter.uriName(), WithDefaultsParameter.uriName());
91 private static final List<String> POSSIBLE_CONTENT = Arrays.stream(ContentParameter.values())
92 .map(ContentParameter::uriValue)
93 .collect(Collectors.toUnmodifiableList());
94 private static final List<String> POSSIBLE_WITH_DEFAULTS = Arrays.stream(WithDefaultsParameter.values())
95 .map(WithDefaultsParameter::uriValue)
96 .collect(Collectors.toUnmodifiableList());
98 private static final String READ_TYPE_TX = "READ";
100 private ReadDataTransactionUtil() {
105 * Parse parameters from URI request and check their types and values.
107 * @param identifier {@link InstanceIdentifierContext}
108 * @param uriInfo URI info
109 * @return {@link QueryParameters}
111 public static QueryParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
112 final UriInfo uriInfo) {
113 final QueryParameters.Builder builder = QueryParameters.builder();
114 if (uriInfo == null) {
115 return builder.build();
118 // check only allowed parameters
119 final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
120 checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
122 // check and set content
123 final String contentStr = getSingleParameter(queryParams, ContentParameter.uriName());
124 if (contentStr != null) {
125 builder.setContent(RestconfDocumentedException.throwIfNull(
126 ContentParameter.forUriValue(contentStr), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
127 "Invalid content parameter: %s, allowed values are %s", contentStr, POSSIBLE_CONTENT));
130 // check and set depth
131 final String depthStr = getSingleParameter(queryParams, DepthParameter.uriName());
132 if (depthStr != null) {
134 builder.setDepth(DepthParameter.forUriValue(depthStr));
135 } catch (IllegalArgumentException e) {
136 throw new RestconfDocumentedException(e, new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
137 "Invalid depth parameter: " + depthStr, null,
138 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
142 // check and set fields
143 final String fieldsStr = getSingleParameter(queryParams, FieldsParameter.uriName());
144 if (fieldsStr != null) {
145 // FIXME: parse a FieldsParameter instead
146 if (identifier.getMountPoint() != null) {
147 builder.setFieldPaths(parseFieldsPaths(identifier, fieldsStr));
149 builder.setFields(parseFieldsParameter(identifier, fieldsStr));
153 // check and set withDefaults parameter
154 final String withDefaultsStr = getSingleParameter(queryParams, WithDefaultsParameter.uriName());
155 if (withDefaultsStr != null) {
156 final WithDefaultsParameter val = WithDefaultsParameter.forUriValue(withDefaultsStr);
158 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
159 "Invalid with-defaults parameter: " + withDefaultsStr, null,
160 "The with-defaults parameter must be a string in " + POSSIBLE_WITH_DEFAULTS));
166 case REPORT_ALL_TAGGED:
167 builder.setTagged(true);
170 builder.setWithDefault(val);
174 return builder.build();
178 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
179 * inside of object {@link RestconfStrategy} provided as a parameter.
181 * @param content type of data to read (config, state, all)
182 * @param path the path to read
183 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
184 * @param withDefa value of with-defaults parameter
185 * @param ctx schema context
186 * @return {@link NormalizedNode}
188 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
189 final @NonNull YangInstanceIdentifier path,
190 final @NonNull RestconfStrategy strategy,
191 final WithDefaultsParameter withDefa,
192 final EffectiveModelContext ctx) {
193 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
196 return readAllData(strategy, path, withDefa, ctx);
198 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
199 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
201 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
203 throw new RestconfDocumentedException(
204 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
205 "Invalid content parameter: " + content.uriValue(), null,
206 "The content parameter value must be either config, nonconfig or all (default)"));
211 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
212 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
214 * @param content type of data to read (config, state, all)
215 * @param path the parent path to read
216 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
217 * @param withDefa value of with-defaults parameter
218 * @param ctx schema context
219 * @param fields paths to selected subtrees which should be read, relative to to the parent path
220 * @return {@link NormalizedNode}
222 public static @Nullable NormalizedNode readData(final @NonNull ContentParameter content,
223 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
224 final @Nullable WithDefaultsParameter withDefa, @NonNull final EffectiveModelContext ctx,
225 final @NonNull List<YangInstanceIdentifier> fields) {
226 // FIXME: use a switch expression when they are available, removing source of RestconfDocumentedException
229 return readAllData(strategy, path, withDefa, ctx, fields);
231 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
233 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
235 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
237 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
238 "Invalid content parameter: " + content.uriValue(), null,
239 "The content parameter value must be either config, nonconfig or all (default)"));
244 static @Nullable String getSingleParameter(final MultivaluedMap<String, String> params, final String name) {
245 final var values = params.get(name);
246 if (values == null) {
250 switch (values.size()) {
254 return verifyNotNull(values.get(0));
256 throw new RestconfDocumentedException("Parameter " + name + " can appear at most once in request URI",
257 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
262 * Check if URI does not contain not allowed parameters for specified operation.
264 * @param usedParameters parameters used in URI request
265 * @param allowedParameters allowed parameters for operation
268 static void checkParametersTypes(final Set<String> usedParameters, final Set<String> allowedParameters) {
269 if (!allowedParameters.containsAll(usedParameters)) {
270 final Set<String> notAllowedParameters = usedParameters.stream()
271 .filter(param -> !allowedParameters.contains(param))
272 .collect(Collectors.toSet());
273 throw new RestconfDocumentedException(
274 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
275 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
279 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
280 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
290 throw new RestconfDocumentedException("Unsupported with-defaults value " + withDefa.uriValue());
293 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
294 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
295 if (result instanceof ContainerNode) {
296 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
297 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
298 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
299 return builder.build();
301 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
302 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
303 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
304 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
305 return builder.build();
309 private static void buildMapEntryBuilder(
310 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
311 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
312 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
313 for (final DataContainerChild child : result.body()) {
314 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
315 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
316 if (child instanceof ContainerNode) {
317 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
318 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
319 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
320 builder.withChild(childBuilder.build());
321 } else if (child instanceof MapNode) {
322 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
323 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
324 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
325 ((ListSchemaNode) childSchema).getKeyDefinition());
326 builder.withChild(childBuilder.build());
327 } else if (child instanceof LeafNode) {
328 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
329 final Object nodeVal = child.body();
330 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
331 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
332 if (keys.contains(child.getIdentifier().getNodeType())) {
333 leafBuilder.withValue(((LeafNode<?>) child).body());
334 builder.withChild(leafBuilder.build());
337 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
338 leafBuilder.withValue(((LeafNode<?>) child).body());
339 builder.withChild(leafBuilder.build());
342 if (defaultVal != null && defaultVal.equals(nodeVal)) {
343 leafBuilder.withValue(((LeafNode<?>) child).body());
344 builder.withChild(leafBuilder.build());
352 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
353 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
354 final boolean trim, final List<QName> keys) {
355 for (final MapEntryNode mapEntryNode : result.body()) {
356 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
357 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
358 .getDataSchemaNode();
359 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
360 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
361 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
362 builder.withChild(mapEntryBuilder.build());
366 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
367 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
368 final YangInstanceIdentifier actualPath, final boolean trim) {
369 for (final DataContainerChild child : result.body()) {
370 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
371 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
372 if (child instanceof ContainerNode) {
373 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
374 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
375 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
376 builder.withChild(builderChild.build());
377 } else if (child instanceof MapNode) {
378 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
379 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
380 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
381 ((ListSchemaNode) childSchema).getKeyDefinition());
382 builder.withChild(childBuilder.build());
383 } else if (child instanceof LeafNode) {
384 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
385 final Object nodeVal = child.body();
386 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
387 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
389 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
390 leafBuilder.withValue(((LeafNode<?>) child).body());
391 builder.withChild(leafBuilder.build());
394 if (defaultVal != null && defaultVal.equals(nodeVal)) {
395 leafBuilder.withValue(((LeafNode<?>) child).body());
396 builder.withChild(leafBuilder.build());
404 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
405 * If don't, we have to read all data from DS (state + config)
407 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
408 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
409 * in {@link RestconfStrategy} if any
410 * @return {@link NormalizedNode}
412 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
413 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
414 return extractReadData(strategy, path, strategy.read(store, path));
418 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
419 * specified subtrees that should only be read.
421 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
422 * @param store datastore type
423 * @param path parent path to selected fields
424 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
425 * in {@link RestconfStrategy} if any
426 * @param fields paths to selected subtrees which should be read, relative to to the parent path
427 * @return {@link NormalizedNode}
429 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
430 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
431 final @NonNull List<YangInstanceIdentifier> fields) {
432 return extractReadData(strategy, path, strategy.read(store, path, fields));
435 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
436 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
437 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
438 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
439 return dataFactory.build();
443 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
444 * {@link RestconfStrategy} provided as a parameter if any.
446 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
447 * @param withDefa with-defaults parameter
448 * @param ctx schema context
449 * @return {@link NormalizedNode}
451 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
452 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
453 // PREPARE STATE DATA NODE
454 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
455 // PREPARE CONFIG DATA NODE
456 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
459 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
460 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
464 * Read config and state data with selected subtrees that should only be read, then map them.
465 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
467 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
468 * @param path parent path to selected fields
469 * @param withDefa with-defaults parameter
470 * @param ctx schema context
471 * @param fields paths to selected subtrees which should be read, relative to to the parent path
472 * @return {@link NormalizedNode}
474 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
475 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParameter withDefa,
476 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
477 // PREPARE STATE DATA NODE
478 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
481 // PREPARE CONFIG DATA NODE
482 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
484 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
485 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
488 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
489 final NormalizedNode configDataNode) {
491 if (stateDataNode == null && configDataNode == null) {
495 // return config data
496 if (stateDataNode == null) {
497 return configDataNode;
501 if (configDataNode == null) {
502 return stateDataNode;
505 // merge data from config and state
506 return mergeStateAndConfigData(stateDataNode, configDataNode);
510 * Merge state and config data into a single NormalizedNode.
512 * @param stateDataNode data node of state data
513 * @param configDataNode data node of config data
514 * @return {@link NormalizedNode}
516 private static @NonNull NormalizedNode mergeStateAndConfigData(
517 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
518 validateNodeMerge(stateDataNode, configDataNode);
519 if (configDataNode instanceof RpcDefinition) {
520 return prepareRpcData(configDataNode, stateDataNode);
522 return prepareData(configDataNode, stateDataNode);
527 * Validates whether the two NormalizedNodes can be merged.
529 * @param stateDataNode data node of state data
530 * @param configDataNode data node of config data
532 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
533 final @NonNull NormalizedNode configDataNode) {
534 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
535 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
536 if (!moduleOfStateData.equals(moduleOfConfigData)) {
537 throw new RestconfDocumentedException("Unable to merge data from different modules.");
542 * Prepare and map data for rpc.
544 * @param configDataNode data node of config data
545 * @param stateDataNode data node of state data
546 * @return {@link NormalizedNode}
548 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
549 final @NonNull NormalizedNode stateDataNode) {
550 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
552 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
555 mapRpcDataNode(configDataNode, mapEntryBuilder);
557 mapRpcDataNode(stateDataNode, mapEntryBuilder);
559 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
560 .addChild(mapEntryBuilder.build())
565 * Map node to map entry builder.
567 * @param dataNode data node
568 * @param mapEntryBuilder builder for mapping data
570 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
571 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
572 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
576 * Prepare and map all data from DS.
578 * @param configDataNode data node of config data
579 * @param stateDataNode data node of state data
580 * @return {@link NormalizedNode}
582 @SuppressWarnings("unchecked")
583 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
584 final @NonNull NormalizedNode stateDataNode) {
585 if (configDataNode instanceof UserMapNode) {
586 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
587 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
590 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
592 return builder.build();
593 } else if (configDataNode instanceof MapNode) {
594 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
595 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
598 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
600 return builder.build();
601 } else if (configDataNode instanceof MapEntryNode) {
602 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
603 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
606 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
608 return builder.build();
609 } else if (configDataNode instanceof ContainerNode) {
610 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
611 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
614 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
616 return builder.build();
617 } else if (configDataNode instanceof AugmentationNode) {
618 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
619 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
621 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
622 ((AugmentationNode) stateDataNode).body(), builder);
624 return builder.build();
625 } else if (configDataNode instanceof ChoiceNode) {
626 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
627 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
630 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
632 return builder.build();
633 } else if (configDataNode instanceof LeafNode) {
634 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
635 } else if (configDataNode instanceof UserLeafSetNode) {
636 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
637 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
639 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
640 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
641 return builder.build();
642 } else if (configDataNode instanceof LeafSetNode) {
643 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
644 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
646 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
647 ((LeafSetNode<Object>) stateDataNode).body(), builder);
648 return builder.build();
649 } else if (configDataNode instanceof LeafSetEntryNode) {
650 return Builders.leafSetEntryBuilder()
651 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
652 .withValue(configDataNode.body())
654 } else if (configDataNode instanceof UnkeyedListNode) {
655 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
656 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
658 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
659 ((UnkeyedListNode) stateDataNode).body(), builder);
660 return builder.build();
661 } else if (configDataNode instanceof UnkeyedListEntryNode) {
662 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
663 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
665 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
666 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
667 return builder.build();
669 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
674 * Map value from container node to builder.
676 * @param configData collection of config data nodes
677 * @param stateData collection of state data nodes
678 * @param builder builder
680 private static <T extends NormalizedNode> void mapValueToBuilder(
681 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
682 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
683 final Map<PathArgument, T> configMap = configData.stream().collect(
684 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
685 final Map<PathArgument, T> stateMap = stateData.stream().collect(
686 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
688 // merge config and state data of children with different identifiers
689 mapDataToBuilder(configMap, stateMap, builder);
691 // merge config and state data of children with the same identifiers
692 mergeDataToBuilder(configMap, stateMap, builder);
696 * Map data with different identifiers to builder. Data with different identifiers can be just added
697 * as childs to parent node.
699 * @param configMap map of config data nodes
700 * @param stateMap map of state data nodes
701 * @param builder - builder
703 private static <T extends NormalizedNode> void mapDataToBuilder(
704 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
705 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
706 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
707 y -> builder.addChild(y.getValue()));
708 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
709 y -> builder.addChild(y.getValue()));
713 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
714 * go one level down with {@code prepareData} method.
716 * @param configMap immutable config data
717 * @param stateMap immutable state data
718 * @param builder - builder
720 @SuppressWarnings("unchecked")
721 private static <T extends NormalizedNode> void mergeDataToBuilder(
722 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
723 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
724 // it is enough to process only config data because operational contains the same data
725 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
726 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));