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 com.google.common.util.concurrent.ListenableFuture;
11 import java.util.Collection;
12 import java.util.List;
14 import java.util.NoSuchElementException;
15 import java.util.Optional;
16 import java.util.function.Function;
17 import java.util.stream.Collectors;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
21 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
22 import org.opendaylight.restconf.api.query.ContentParam;
23 import org.opendaylight.restconf.api.query.WithDefaultsParam;
24 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
25 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
48 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
49 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
50 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
51 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
53 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
54 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
55 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
56 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * Util class for read data from data store via transaction.
67 * <li>all (config + state)
70 public final class ReadDataTransactionUtil {
71 private static final Logger LOG = LoggerFactory.getLogger(ReadDataTransactionUtil.class);
73 private ReadDataTransactionUtil() {
78 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
79 * inside of object {@link RestconfStrategy} provided as a parameter.
81 * @param content type of data to read (config, state, all)
82 * @param path the path to read
83 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
84 * @param withDefa value of with-defaults parameter
85 * @param ctx schema context
86 * @return {@link NormalizedNode}
88 public static @Nullable NormalizedNode readData(final @NonNull ContentParam content,
89 final @NonNull YangInstanceIdentifier path,
90 final @NonNull RestconfStrategy strategy,
91 final WithDefaultsParam withDefa,
92 final EffectiveModelContext ctx) {
93 return switch (content) {
94 case ALL -> readAllData(strategy, path, withDefa, ctx);
96 final var read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
97 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
99 case NONCONFIG -> readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
104 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
105 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
107 * @param content type of data to read (config, state, all)
108 * @param path the parent path to read
109 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
110 * @param withDefa value of with-defaults parameter
111 * @param ctx schema context
112 * @param fields paths to selected subtrees which should be read, relative to to the parent path
113 * @return {@link NormalizedNode}
115 public static @Nullable NormalizedNode readData(final @NonNull ContentParam content,
116 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
117 final @Nullable WithDefaultsParam withDefa, @NonNull final EffectiveModelContext ctx,
118 final @NonNull List<YangInstanceIdentifier> fields) {
119 return switch (content) {
120 case ALL -> readAllData(strategy, path, withDefa, ctx, fields);
122 final var read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, fields);
123 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
125 case NONCONFIG -> readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
129 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData,
130 final YangInstanceIdentifier path, final WithDefaultsParam withDefa, final EffectiveModelContext ctx) {
131 final boolean trim = switch (withDefa) {
133 case EXPLICIT -> false;
134 case REPORT_ALL, REPORT_ALL_TAGGED -> throw new RestconfDocumentedException(
135 "Unsupported with-defaults value " + withDefa.paramValue());
138 final var ctxNode = DataSchemaContextTree.from(ctx).findChild(path).orElseThrow();
139 if (readData instanceof ContainerNode container) {
140 final var builder = Builders.containerBuilder().withNodeIdentifier(container.getIdentifier());
141 buildCont(builder, container.body(), ctxNode, trim);
142 return builder.build();
143 } else if (readData instanceof MapEntryNode mapEntry) {
144 if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
145 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
148 final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.getIdentifier());
149 buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
150 return builder.build();
152 throw new IllegalStateException("Unhandled data contract " + readData.contract());
156 private static void buildMapEntryBuilder(
157 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
158 final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
159 final boolean trim, final List<QName> keys) {
160 for (var child : children) {
161 final var childCtx = getChildContext(ctxNode, child);
163 if (child instanceof ContainerNode container) {
164 appendContainer(builder, container, childCtx, trim);
165 } else if (child instanceof MapNode map) {
166 appendMap(builder, map, childCtx, trim);
167 } else if (child instanceof LeafNode<?> leaf) {
168 appendLeaf(builder, leaf, childCtx, trim, keys);
170 // FIXME: we should never hit this, throw an ISE if this ever happens
171 LOG.debug("Ignoring unhandled child contract {}", child.contract());
176 private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
177 final DataSchemaContext ctxNode, final boolean trim) {
178 final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.getIdentifier());
179 buildCont(childBuilder, container.body(), ctxNode, trim);
180 builder.withChild(childBuilder.build());
183 private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
184 final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
185 if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
186 throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
189 // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
190 final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
192 // This is a combined check for when we need to emit the leaf.
194 // We always have to emit key leaf values
195 keys.contains(leafSchema.getQName())
196 // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
198 // When data is retrieved with a <with-defaults> parameter equal to
199 // 'trim', data nodes MUST NOT be reported if they contain the schema
200 // default value. Non-configuration data nodes containing the schema
201 // default value MUST NOT be reported.
203 || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
204 // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
205 // grasp what we are doing here... emit only if it matches default ???!!!
206 // FIXME: The WithDefaultsParam.EXPLICIT says:
208 // Data nodes set to the YANG default by the client are reported.
210 // and RFC8040 (https://datatracker.ietf.org/doc/html/rfc8040#page-60) says:
212 // If the "with-defaults" parameter is set to "explicit", then the
213 // server MUST adhere to the default-reporting behavior defined in
214 // Section 3.3 of [RFC6243].
216 // and then RFC6243 says:
218 // When data is retrieved with a <with-defaults> parameter equal to
219 // 'explicit', a data node that was set by a client to its schema
220 // default value MUST be reported. A conceptual data node that would be
221 // set by the server to the schema default value MUST NOT be reported.
222 // Non-configuration data nodes containing the schema default value MUST
225 // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
226 // This seems to disregard the 'trim = true' case semantics (see above).
227 // Combining the above, though, these checks are missing the 'non-config' check, which would
228 // distinguish, but barring that this check is superfluous and results in the wrong semantics.
229 // Without that input, this really should be covered by the previous case.
230 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
231 builder.withChild(leaf);
235 private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
236 final DataSchemaContext childCtx, final boolean trim) {
237 if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
238 throw new IllegalStateException("Input " + map + " does not match " + childCtx);
241 final var childBuilder = switch (map.ordering()) {
242 case SYSTEM -> Builders.mapBuilder();
243 case USER -> Builders.orderedMapBuilder();
245 buildList(childBuilder.withNodeIdentifier(map.getIdentifier()), map.body(), childCtx, trim,
246 listSchema.getKeyDefinition());
247 builder.withChild(childBuilder.build());
250 private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
251 final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
252 final List<@NonNull QName> keys) {
253 for (var entry : entries) {
254 final var childCtx = getChildContext(ctxNode, entry);
255 final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.getIdentifier());
256 buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
257 builder.withChild(mapEntryBuilder.build());
261 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
262 final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
263 for (var child : children) {
264 final var childCtx = getChildContext(ctxNode, child);
265 if (child instanceof ContainerNode container) {
266 appendContainer(builder, container, childCtx, trim);
267 } else if (child instanceof MapNode map) {
268 appendMap(builder, map, childCtx, trim);
269 } else if (child instanceof LeafNode<?> leaf) {
270 appendLeaf(builder, leaf, childCtx, trim, List.of());
275 private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
276 final NormalizedNode child) {
277 final var childId = child.name();
278 final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
280 if (childCtx == null) {
281 throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
287 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
288 * If don't, we have to read all data from DS (state + config)
290 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
291 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
292 * in {@link RestconfStrategy} if any
293 * @return {@link NormalizedNode}
295 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
296 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
297 return extractReadData(strategy, path, strategy.read(store, path));
301 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
302 * specified subtrees that should only be read.
304 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
305 * @param store datastore type
306 * @param path parent path to selected fields
307 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
308 * in {@link RestconfStrategy} if any
309 * @param fields paths to selected subtrees which should be read, relative to to the parent path
310 * @return {@link NormalizedNode}
312 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
313 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
314 final @NonNull List<YangInstanceIdentifier> fields) {
315 return extractReadData(strategy, path, strategy.read(store, path, fields));
318 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
319 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
320 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
321 FutureCallbackTx.addCallback(dataFuture, "READ", dataFactory, path);
322 return dataFactory.build();
326 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
327 * {@link RestconfStrategy} provided as a parameter if any.
329 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
330 * @param withDefa with-defaults parameter
331 * @param ctx schema context
332 * @return {@link NormalizedNode}
334 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
335 final YangInstanceIdentifier path, final WithDefaultsParam withDefa, final EffectiveModelContext ctx) {
336 // PREPARE STATE DATA NODE
337 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
338 // PREPARE CONFIG DATA NODE
339 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
342 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
343 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
347 * Read config and state data with selected subtrees that should only be read, then map them.
348 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
350 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
351 * @param path parent path to selected fields
352 * @param withDefa with-defaults parameter
353 * @param ctx schema context
354 * @param fields paths to selected subtrees which should be read, relative to to the parent path
355 * @return {@link NormalizedNode}
357 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
358 final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
359 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
360 // PREPARE STATE DATA NODE
361 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
364 // PREPARE CONFIG DATA NODE
365 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
367 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
368 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
371 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
372 final NormalizedNode configDataNode) {
374 if (stateDataNode == null && configDataNode == null) {
378 // return config data
379 if (stateDataNode == null) {
380 return configDataNode;
384 if (configDataNode == null) {
385 return stateDataNode;
388 // merge data from config and state
389 return mergeStateAndConfigData(stateDataNode, configDataNode);
393 * Merge state and config data into a single NormalizedNode.
395 * @param stateDataNode data node of state data
396 * @param configDataNode data node of config data
397 * @return {@link NormalizedNode}
399 private static @NonNull NormalizedNode mergeStateAndConfigData(
400 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
401 validateNodeMerge(stateDataNode, configDataNode);
402 if (configDataNode instanceof RpcDefinition) {
403 return prepareRpcData(configDataNode, stateDataNode);
405 return prepareData(configDataNode, stateDataNode);
410 * Validates whether the two NormalizedNodes can be merged.
412 * @param stateDataNode data node of state data
413 * @param configDataNode data node of config data
415 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
416 final @NonNull NormalizedNode configDataNode) {
417 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
418 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
419 if (!moduleOfStateData.equals(moduleOfConfigData)) {
420 throw new RestconfDocumentedException("Unable to merge data from different modules.");
425 * Prepare and map data for rpc.
427 * @param configDataNode data node of config data
428 * @param stateDataNode data node of state data
429 * @return {@link NormalizedNode}
431 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
432 final @NonNull NormalizedNode stateDataNode) {
433 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
435 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
438 mapRpcDataNode(configDataNode, mapEntryBuilder);
440 mapRpcDataNode(stateDataNode, mapEntryBuilder);
442 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
443 .addChild(mapEntryBuilder.build())
448 * Map node to map entry builder.
450 * @param dataNode data node
451 * @param mapEntryBuilder builder for mapping data
453 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
454 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
455 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
459 * Prepare and map all data from DS.
461 * @param configDataNode data node of config data
462 * @param stateDataNode data node of state data
463 * @return {@link NormalizedNode}
465 @SuppressWarnings("unchecked")
466 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
467 final @NonNull NormalizedNode stateDataNode) {
468 if (configDataNode instanceof UserMapNode) {
469 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
470 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
473 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
475 return builder.build();
476 } else if (configDataNode instanceof MapNode) {
477 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
478 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
481 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
483 return builder.build();
484 } else if (configDataNode instanceof MapEntryNode) {
485 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
486 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
489 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
491 return builder.build();
492 } else if (configDataNode instanceof ContainerNode) {
493 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
494 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
497 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
499 return builder.build();
500 } else if (configDataNode instanceof ChoiceNode) {
501 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
502 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
505 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
507 return builder.build();
508 } else if (configDataNode instanceof LeafNode) {
509 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
510 } else if (configDataNode instanceof UserLeafSetNode) {
511 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
512 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
514 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
515 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
516 return builder.build();
517 } else if (configDataNode instanceof LeafSetNode) {
518 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
519 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
521 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
522 ((LeafSetNode<Object>) stateDataNode).body(), builder);
523 return builder.build();
524 } else if (configDataNode instanceof LeafSetEntryNode) {
525 return Builders.leafSetEntryBuilder()
526 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
527 .withValue(configDataNode.body())
529 } else if (configDataNode instanceof UnkeyedListNode) {
530 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
531 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
533 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
534 ((UnkeyedListNode) stateDataNode).body(), builder);
535 return builder.build();
536 } else if (configDataNode instanceof UnkeyedListEntryNode) {
537 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
538 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
540 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
541 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
542 return builder.build();
544 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
549 * Map value from container node to builder.
551 * @param configData collection of config data nodes
552 * @param stateData collection of state data nodes
553 * @param builder builder
555 private static <T extends NormalizedNode> void mapValueToBuilder(
556 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
557 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
558 final Map<PathArgument, T> configMap = configData.stream().collect(
559 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
560 final Map<PathArgument, T> stateMap = stateData.stream().collect(
561 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
563 // merge config and state data of children with different identifiers
564 mapDataToBuilder(configMap, stateMap, builder);
566 // merge config and state data of children with the same identifiers
567 mergeDataToBuilder(configMap, stateMap, builder);
571 * Map data with different identifiers to builder. Data with different identifiers can be just added
572 * as childs to parent node.
574 * @param configMap map of config data nodes
575 * @param stateMap map of state data nodes
576 * @param builder - builder
578 private static <T extends NormalizedNode> void mapDataToBuilder(
579 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
580 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
581 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
582 y -> builder.addChild(y.getValue()));
583 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
584 y -> builder.addChild(y.getValue()));
588 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
589 * go one level down with {@code prepareData} method.
591 * @param configMap immutable config data
592 * @param stateMap immutable state data
593 * @param builder - builder
595 @SuppressWarnings("unchecked")
596 private static <T extends NormalizedNode> void mergeDataToBuilder(
597 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
598 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
599 // it is enough to process only config data because operational contains the same data
600 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
601 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));