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.annotations.VisibleForTesting;
11 import com.google.common.collect.Sets;
12 import com.google.common.primitives.Ints;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.List;
18 import java.util.Optional;
20 import java.util.function.Function;
21 import java.util.stream.Collectors;
22 import javax.ws.rs.core.UriInfo;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
26 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
27 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.context.WriterParameters;
29 import org.opendaylight.restconf.common.context.WriterParameters.WriterParametersBuilder;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
33 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
34 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
35 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.ReadData.WithDefaults;
36 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
48 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
65 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
66 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
69 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
74 * Util class for read data from data store via transaction.
78 * <li>all (config + state)
81 public final class ReadDataTransactionUtil {
82 private static final String READ_TYPE_TX = "READ";
84 private ReadDataTransactionUtil() {
85 throw new UnsupportedOperationException("Util class.");
89 * Parse parameters from URI request and check their types and values.
91 * @param identifier {@link InstanceIdentifierContext}
92 * @param uriInfo URI info
93 * @return {@link WriterParameters}
95 public static WriterParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
96 final UriInfo uriInfo) {
97 final WriterParametersBuilder builder = new WriterParametersBuilder();
99 if (uriInfo == null) {
100 return builder.build();
103 // check only allowed parameters
104 checkParametersTypes(uriInfo.getQueryParameters().keySet(),
105 RestconfDataServiceConstant.ReadData.CONTENT,
106 RestconfDataServiceConstant.ReadData.DEPTH,
107 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
109 // read parameters from URI or set default values
110 final List<String> content = uriInfo.getQueryParameters().getOrDefault(
111 RestconfDataServiceConstant.ReadData.CONTENT,
112 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
113 final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
114 RestconfDataServiceConstant.ReadData.DEPTH,
115 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
116 final List<String> withDefaults = uriInfo.getQueryParameters().getOrDefault(
117 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS,
118 Collections.emptyList());
120 final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
121 RestconfDataServiceConstant.ReadData.FIELDS,
122 Collections.emptyList());
124 // parameter can be in URI at most once
125 checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
126 checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
127 checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
128 checkParameterCount(fields, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
130 // check and set content
131 final String contentValue = content.get(0);
132 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
133 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
134 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
135 throw new RestconfDocumentedException(
136 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
137 "Invalid content parameter: " + contentValue, null,
138 "The content parameter value must be either config, nonconfig or all (default)"));
142 builder.setContent(content.get(0));
144 // check and set depth
145 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
146 final Integer value = Ints.tryParse(depth.get(0));
148 if (value == null || value < RestconfDataServiceConstant.ReadData.MIN_DEPTH
149 || value > RestconfDataServiceConstant.ReadData.MAX_DEPTH) {
150 throw new RestconfDocumentedException(
151 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
152 "Invalid depth parameter: " + depth, null,
153 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
155 builder.setDepth(value);
159 // check and set fields
160 if (!fields.isEmpty()) {
161 builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
164 // check and set withDefaults parameter
165 if (!withDefaults.isEmpty()) {
166 final String str = withDefaults.get(0);
167 final WithDefaults val = WithDefaults.forValue(str);
169 throw new RestconfDocumentedException(new RestconfError(RestconfError.ErrorType.PROTOCOL,
170 RestconfError.ErrorTag.INVALID_VALUE, "Invalid with-defaults parameter: " + str, null,
171 "The with-defaults parameter must be a string in " + WithDefaults.possibleValues()));
177 case REPORT_ALL_TAGGED:
178 builder.setTagged(true);
181 builder.setWithDefault(val.value());
184 return builder.build();
188 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
189 * inside of object {@link RestconfStrategy} provided as a parameter.
191 * @param valueOfContent type of data to read (config, state, all)
192 * @param path the path to read
193 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
194 * @param withDefa value of with-defaults parameter
195 * @param ctx schema context
196 * @return {@link NormalizedNode}
198 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
199 final @NonNull YangInstanceIdentifier path,
200 final @NonNull RestconfStrategy strategy,
201 final String withDefa, final EffectiveModelContext ctx) {
202 switch (valueOfContent) {
203 case RestconfDataServiceConstant.ReadData.CONFIG:
204 if (withDefa == null) {
205 return readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true);
207 return prepareDataByParamWithDef(
208 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
209 path, withDefa, ctx);
211 case RestconfDataServiceConstant.ReadData.NONCONFIG:
212 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, true);
213 case RestconfDataServiceConstant.ReadData.ALL:
214 return readAllData(strategy, path, withDefa, ctx);
217 throw new RestconfDocumentedException(
218 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
219 "Invalid content parameter: " + valueOfContent, null,
220 "The content parameter value must be either config, nonconfig or all (default)"));
226 * Check if URI does not contain value for the same parameter more than once.
228 * @param parameterValues URI parameter values
229 * @param parameterName URI parameter name
232 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
233 if (parameterValues.size() > 1) {
234 throw new RestconfDocumentedException(
235 "Parameter " + parameterName + " can appear at most once in request URI",
236 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
241 * Check if URI does not contain not allowed parameters for specified operation.
243 * @param usedParameters parameters used in URI request
244 * @param allowedParameters allowed parameters for operation
247 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
248 final @NonNull String... allowedParameters) {
249 // FIXME: there should be a speedier way to do this
250 final Set<String> notAllowedParameters = Sets.newHashSet(usedParameters);
251 notAllowedParameters.removeAll(Sets.newHashSet(allowedParameters));
253 if (!notAllowedParameters.isEmpty()) {
254 throw new RestconfDocumentedException(
255 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
256 RestconfError.ErrorType.PROTOCOL,
257 RestconfError.ErrorTag.INVALID_VALUE);
261 private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
262 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
272 throw new RestconfDocumentedException("");
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 Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
280 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
281 return builder.build();
283 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
284 Builders.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<? extends PathArgument, ?> child : result.getValue()) {
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 Builders.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, MapNode> childBuilder =
305 Builders.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.getValue();
312 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
313 Builders.leafBuilder((LeafSchemaNode) childSchema);
314 if (keys.contains(child.getNodeType())) {
315 leafBuilder.withValue(((LeafNode<?>) child).getValue());
316 builder.withChild(leafBuilder.build());
319 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
320 leafBuilder.withValue(((LeafNode<?>) child).getValue());
321 builder.withChild(leafBuilder.build());
324 if (defaultVal != null && defaultVal.equals(nodeVal)) {
325 leafBuilder.withValue(((LeafNode<?>) child).getValue());
326 builder.withChild(leafBuilder.build());
334 private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
335 final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
336 final List<QName> keys) {
337 for (final MapEntryNode mapEntryNode : result.getValue()) {
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 Builders.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<? extends PathArgument, ?> child : result.getValue()) {
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 Builders.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, MapNode> childBuilder =
361 Builders.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.getValue();
368 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
369 Builders.leafBuilder((LeafSchemaNode) childSchema);
371 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
372 leafBuilder.withValue(((LeafNode<?>) child).getValue());
373 builder.withChild(leafBuilder.build());
376 if (defaultVal != null && defaultVal.equals(nodeVal)) {
377 leafBuilder.withValue(((LeafNode<?>) child).getValue());
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 final boolean closeTransactionChain) {
397 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
398 final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = strategy.read(store, path);
399 if (closeTransactionChain) {
400 //Method close transactionChain if any
401 FutureCallbackTx.addCallback(listenableFuture, READ_TYPE_TX, dataFactory, strategy, path);
403 FutureCallbackTx.addCallback(listenableFuture, READ_TYPE_TX, dataFactory);
405 return dataFactory.build();
409 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
410 * {@link RestconfStrategy} provided as a parameter if any.
412 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
413 * @param withDefa with-defaults parameter
414 * @param ctx schema context
415 * @return {@link NormalizedNode}
417 private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull RestconfStrategy strategy,
418 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
419 // PREPARE STATE DATA NODE
420 final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(
421 strategy, LogicalDatastoreType.OPERATIONAL, path, false);
423 // PREPARE CONFIG DATA NODE
424 final NormalizedNode<?, ?> configDataNode;
425 //Here will be closed transactionChain if any
426 if (withDefa == null) {
427 configDataNode = readDataViaTransaction(
428 strategy, LogicalDatastoreType.CONFIGURATION, path, true);
430 configDataNode = prepareDataByParamWithDef(
431 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
432 path, withDefa, ctx);
436 if (stateDataNode == null && configDataNode == null) {
440 // return config data
441 if (stateDataNode == null) {
442 return configDataNode;
446 if (configDataNode == null) {
447 return stateDataNode;
450 // merge data from config and state
451 return mergeStateAndConfigData(stateDataNode, configDataNode);
455 * Merge state and config data into a single NormalizedNode.
457 * @param stateDataNode data node of state data
458 * @param configDataNode data node of config data
459 * @return {@link NormalizedNode}
461 private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
462 final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
463 validateNodeMerge(stateDataNode, configDataNode);
464 if (configDataNode instanceof RpcDefinition) {
465 return prepareRpcData(configDataNode, stateDataNode);
467 return prepareData(configDataNode, stateDataNode);
472 * Validates whether the two NormalizedNodes can be merged.
474 * @param stateDataNode data node of state data
475 * @param configDataNode data node of config data
477 private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
478 final @NonNull NormalizedNode<?, ?> configDataNode) {
479 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
480 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
481 if (!moduleOfStateData.equals(moduleOfConfigData)) {
482 throw new RestconfDocumentedException("Unable to merge data from different modules.");
487 * Prepare and map data for rpc.
489 * @param configDataNode data node of config data
490 * @param stateDataNode data node of state data
491 * @return {@link NormalizedNode}
493 private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
494 final @NonNull NormalizedNode<?, ?> stateDataNode) {
495 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
497 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
500 mapRpcDataNode(configDataNode, mapEntryBuilder);
502 mapRpcDataNode(stateDataNode, mapEntryBuilder);
504 return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
508 * Map node to map entry builder.
510 * @param dataNode data node
511 * @param mapEntryBuilder builder for mapping data
513 private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
514 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
515 ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
519 * Prepare and map all data from DS.
521 * @param configDataNode data node of config data
522 * @param stateDataNode data node of state data
523 * @return {@link NormalizedNode}
525 @SuppressWarnings("unchecked")
526 private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
527 final @NonNull NormalizedNode<?, ?> stateDataNode) {
528 if (configDataNode instanceof OrderedMapNode) {
529 final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
530 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
533 ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
535 return builder.build();
536 } else if (configDataNode instanceof MapNode) {
537 final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
538 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
541 ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
543 return builder.build();
544 } else if (configDataNode instanceof MapEntryNode) {
545 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
546 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
549 ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
551 return builder.build();
552 } else if (configDataNode instanceof ContainerNode) {
553 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
554 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
557 ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
559 return builder.build();
560 } else if (configDataNode instanceof AugmentationNode) {
561 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
562 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
564 mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
565 ((AugmentationNode) stateDataNode).getValue(), builder);
567 return builder.build();
568 } else if (configDataNode instanceof ChoiceNode) {
569 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
570 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
573 ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
575 return builder.build();
576 } else if (configDataNode instanceof LeafNode) {
577 return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
578 } else if (configDataNode instanceof OrderedLeafSetNode) {
579 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
580 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
582 mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
583 ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
584 return builder.build();
585 } else if (configDataNode instanceof LeafSetNode) {
586 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
587 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
589 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
590 ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
591 return builder.build();
592 } else if (configDataNode instanceof LeafSetEntryNode) {
593 return Builders.leafSetEntryBuilder()
594 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
595 .withValue(configDataNode.getValue())
597 } else if (configDataNode instanceof UnkeyedListNode) {
598 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
599 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
601 mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
602 ((UnkeyedListNode) stateDataNode).getValue(), builder);
603 return builder.build();
604 } else if (configDataNode instanceof UnkeyedListEntryNode) {
605 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
606 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
608 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
609 ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
610 return builder.build();
612 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
617 * Map value from container node to builder.
619 * @param configData collection of config data nodes
620 * @param stateData collection of state data nodes
621 * @param builder builder
623 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
624 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
625 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
626 final Map<PathArgument, T> configMap = configData.stream().collect(
627 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
628 final Map<PathArgument, T> stateMap = stateData.stream().collect(
629 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
631 // merge config and state data of children with different identifiers
632 mapDataToBuilder(configMap, stateMap, builder);
634 // merge config and state data of children with the same identifiers
635 mergeDataToBuilder(configMap, stateMap, builder);
639 * Map data with different identifiers to builder. Data with different identifiers can be just added
640 * as childs to parent node.
642 * @param configMap map of config data nodes
643 * @param stateMap map of state data nodes
644 * @param builder - builder
646 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
647 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
648 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
649 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
650 y -> builder.addChild(y.getValue()));
651 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
652 y -> builder.addChild(y.getValue()));
656 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
657 * go one level down with {@code prepareData} method.
659 * @param configMap immutable config data
660 * @param stateMap immutable state data
661 * @param builder - builder
663 @SuppressWarnings("unchecked")
664 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
665 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
666 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
667 // it is enough to process only config data because operational contains the same data
668 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
669 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));