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.databind.jaxrs.UriInfoSupport.getSingleParameter;
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 * Check if URI does not contain not allowed parameters for specified operation.
246 * @param usedParameters parameters used in URI request
247 * @param allowedParameters allowed parameters for operation
250 static void checkParametersTypes(final Set<String> usedParameters, final Set<String> allowedParameters) {
251 if (!allowedParameters.containsAll(usedParameters)) {
252 final Set<String> notAllowedParameters = usedParameters.stream()
253 .filter(param -> !allowedParameters.contains(param))
254 .collect(Collectors.toSet());
255 throw new RestconfDocumentedException(
256 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
257 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
261 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
262 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
272 throw new RestconfDocumentedException("Unsupported with-defaults value " + withDefa.uriValue());
275 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
276 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
277 if (result instanceof ContainerNode) {
278 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
279 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
280 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
281 return builder.build();
283 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
284 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
285 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
286 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
287 return builder.build();
291 private static void buildMapEntryBuilder(
292 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
293 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
294 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
295 for (final DataContainerChild child : result.body()) {
296 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
297 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
298 if (child instanceof ContainerNode) {
299 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
300 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
301 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
302 builder.withChild(childBuilder.build());
303 } else if (child instanceof MapNode) {
304 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
305 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
306 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
307 ((ListSchemaNode) childSchema).getKeyDefinition());
308 builder.withChild(childBuilder.build());
309 } else if (child instanceof LeafNode) {
310 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
311 final Object nodeVal = child.body();
312 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
313 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
314 if (keys.contains(child.getIdentifier().getNodeType())) {
315 leafBuilder.withValue(((LeafNode<?>) child).body());
316 builder.withChild(leafBuilder.build());
319 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
320 leafBuilder.withValue(((LeafNode<?>) child).body());
321 builder.withChild(leafBuilder.build());
324 if (defaultVal != null && defaultVal.equals(nodeVal)) {
325 leafBuilder.withValue(((LeafNode<?>) child).body());
326 builder.withChild(leafBuilder.build());
334 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
335 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
336 final boolean trim, final List<QName> keys) {
337 for (final MapEntryNode mapEntryNode : result.body()) {
338 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
339 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
340 .getDataSchemaNode();
341 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
342 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
343 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
344 builder.withChild(mapEntryBuilder.build());
348 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
349 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
350 final YangInstanceIdentifier actualPath, final boolean trim) {
351 for (final DataContainerChild child : result.body()) {
352 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
353 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
354 if (child instanceof ContainerNode) {
355 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
356 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
357 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
358 builder.withChild(builderChild.build());
359 } else if (child instanceof MapNode) {
360 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
361 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
362 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
363 ((ListSchemaNode) childSchema).getKeyDefinition());
364 builder.withChild(childBuilder.build());
365 } else if (child instanceof LeafNode) {
366 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
367 final Object nodeVal = child.body();
368 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
369 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
371 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
372 leafBuilder.withValue(((LeafNode<?>) child).body());
373 builder.withChild(leafBuilder.build());
376 if (defaultVal != null && defaultVal.equals(nodeVal)) {
377 leafBuilder.withValue(((LeafNode<?>) child).body());
378 builder.withChild(leafBuilder.build());
386 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
387 * If don't, we have to read all data from DS (state + config)
389 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
390 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
391 * in {@link RestconfStrategy} if any
392 * @return {@link NormalizedNode}
394 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
395 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
396 return extractReadData(strategy, path, strategy.read(store, path));
400 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
401 * specified subtrees that should only be read.
403 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
404 * @param store datastore type
405 * @param path parent path to selected fields
406 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
407 * in {@link RestconfStrategy} if any
408 * @param fields paths to selected subtrees which should be read, relative to to the parent path
409 * @return {@link NormalizedNode}
411 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
412 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
413 final @NonNull List<YangInstanceIdentifier> fields) {
414 return extractReadData(strategy, path, strategy.read(store, path, fields));
417 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
418 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
419 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
420 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
421 return dataFactory.build();
425 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
426 * {@link RestconfStrategy} provided as a parameter if any.
428 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
429 * @param withDefa with-defaults parameter
430 * @param ctx schema context
431 * @return {@link NormalizedNode}
433 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
434 final YangInstanceIdentifier path, final WithDefaultsParameter withDefa, final EffectiveModelContext ctx) {
435 // PREPARE STATE DATA NODE
436 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
437 // PREPARE CONFIG DATA NODE
438 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
441 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
442 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
446 * Read config and state data with selected subtrees that should only be read, then map them.
447 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
449 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
450 * @param path parent path to selected fields
451 * @param withDefa with-defaults parameter
452 * @param ctx schema context
453 * @param fields paths to selected subtrees which should be read, relative to to the parent path
454 * @return {@link NormalizedNode}
456 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
457 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParameter withDefa,
458 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
459 // PREPARE STATE DATA NODE
460 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
463 // PREPARE CONFIG DATA NODE
464 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
466 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
467 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
470 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
471 final NormalizedNode configDataNode) {
473 if (stateDataNode == null && configDataNode == null) {
477 // return config data
478 if (stateDataNode == null) {
479 return configDataNode;
483 if (configDataNode == null) {
484 return stateDataNode;
487 // merge data from config and state
488 return mergeStateAndConfigData(stateDataNode, configDataNode);
492 * Merge state and config data into a single NormalizedNode.
494 * @param stateDataNode data node of state data
495 * @param configDataNode data node of config data
496 * @return {@link NormalizedNode}
498 private static @NonNull NormalizedNode mergeStateAndConfigData(
499 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
500 validateNodeMerge(stateDataNode, configDataNode);
501 if (configDataNode instanceof RpcDefinition) {
502 return prepareRpcData(configDataNode, stateDataNode);
504 return prepareData(configDataNode, stateDataNode);
509 * Validates whether the two NormalizedNodes can be merged.
511 * @param stateDataNode data node of state data
512 * @param configDataNode data node of config data
514 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
515 final @NonNull NormalizedNode configDataNode) {
516 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
517 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
518 if (!moduleOfStateData.equals(moduleOfConfigData)) {
519 throw new RestconfDocumentedException("Unable to merge data from different modules.");
524 * Prepare and map data for rpc.
526 * @param configDataNode data node of config data
527 * @param stateDataNode data node of state data
528 * @return {@link NormalizedNode}
530 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
531 final @NonNull NormalizedNode stateDataNode) {
532 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
534 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
537 mapRpcDataNode(configDataNode, mapEntryBuilder);
539 mapRpcDataNode(stateDataNode, mapEntryBuilder);
541 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
542 .addChild(mapEntryBuilder.build())
547 * Map node to map entry builder.
549 * @param dataNode data node
550 * @param mapEntryBuilder builder for mapping data
552 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
553 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
554 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
558 * Prepare and map all data from DS.
560 * @param configDataNode data node of config data
561 * @param stateDataNode data node of state data
562 * @return {@link NormalizedNode}
564 @SuppressWarnings("unchecked")
565 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
566 final @NonNull NormalizedNode stateDataNode) {
567 if (configDataNode instanceof UserMapNode) {
568 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
569 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
572 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
574 return builder.build();
575 } else if (configDataNode instanceof MapNode) {
576 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
577 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
580 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
582 return builder.build();
583 } else if (configDataNode instanceof MapEntryNode) {
584 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
585 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
588 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
590 return builder.build();
591 } else if (configDataNode instanceof ContainerNode) {
592 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
593 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
596 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
598 return builder.build();
599 } else if (configDataNode instanceof AugmentationNode) {
600 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
601 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
603 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
604 ((AugmentationNode) stateDataNode).body(), builder);
606 return builder.build();
607 } else if (configDataNode instanceof ChoiceNode) {
608 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
609 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
612 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
614 return builder.build();
615 } else if (configDataNode instanceof LeafNode) {
616 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
617 } else if (configDataNode instanceof UserLeafSetNode) {
618 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
619 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
621 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
622 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
623 return builder.build();
624 } else if (configDataNode instanceof LeafSetNode) {
625 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
626 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
628 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
629 ((LeafSetNode<Object>) stateDataNode).body(), builder);
630 return builder.build();
631 } else if (configDataNode instanceof LeafSetEntryNode) {
632 return Builders.leafSetEntryBuilder()
633 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
634 .withValue(configDataNode.body())
636 } else if (configDataNode instanceof UnkeyedListNode) {
637 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
638 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
640 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
641 ((UnkeyedListNode) stateDataNode).body(), builder);
642 return builder.build();
643 } else if (configDataNode instanceof UnkeyedListEntryNode) {
644 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
645 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
647 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
648 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
649 return builder.build();
651 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
656 * Map value from container node to builder.
658 * @param configData collection of config data nodes
659 * @param stateData collection of state data nodes
660 * @param builder builder
662 private static <T extends NormalizedNode> void mapValueToBuilder(
663 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
664 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
665 final Map<PathArgument, T> configMap = configData.stream().collect(
666 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
667 final Map<PathArgument, T> stateMap = stateData.stream().collect(
668 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
670 // merge config and state data of children with different identifiers
671 mapDataToBuilder(configMap, stateMap, builder);
673 // merge config and state data of children with the same identifiers
674 mergeDataToBuilder(configMap, stateMap, builder);
678 * Map data with different identifiers to builder. Data with different identifiers can be just added
679 * as childs to parent node.
681 * @param configMap map of config data nodes
682 * @param stateMap map of state data nodes
683 * @param builder - builder
685 private static <T extends NormalizedNode> void mapDataToBuilder(
686 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
687 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
688 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
689 y -> builder.addChild(y.getValue()));
690 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
691 y -> builder.addChild(y.getValue()));
695 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
696 * go one level down with {@code prepareData} method.
698 * @param configMap immutable config data
699 * @param stateMap immutable state data
700 * @param builder - builder
702 @SuppressWarnings("unchecked")
703 private static <T extends NormalizedNode> void mergeDataToBuilder(
704 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
705 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
706 // it is enough to process only config data because operational contains the same data
707 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
708 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));