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.utils.parser.ParserFieldsParameter;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
43 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
47 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
57 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
58 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
64 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
73 * Util class for read data from data store via transaction.
77 * <li>all (config + state)
80 public final class ReadDataTransactionUtil {
81 private static final String READ_TYPE_TX = "READ";
83 private ReadDataTransactionUtil() {
84 throw new UnsupportedOperationException("Util class.");
88 * Parse parameters from URI request and check their types and values.
90 * @param identifier {@link InstanceIdentifierContext}
91 * @param uriInfo URI info
92 * @return {@link WriterParameters}
94 public static WriterParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
95 final UriInfo uriInfo) {
96 final WriterParametersBuilder builder = new WriterParametersBuilder();
98 if (uriInfo == null) {
99 return builder.build();
102 // check only allowed parameters
103 checkParametersTypes(uriInfo.getQueryParameters().keySet(),
104 RestconfDataServiceConstant.ReadData.CONTENT,
105 RestconfDataServiceConstant.ReadData.DEPTH,
106 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
108 // read parameters from URI or set default values
109 final List<String> content = uriInfo.getQueryParameters().getOrDefault(
110 RestconfDataServiceConstant.ReadData.CONTENT,
111 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
112 final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
113 RestconfDataServiceConstant.ReadData.DEPTH,
114 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
115 final List<String> withDefaults = uriInfo.getQueryParameters().getOrDefault(
116 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS,
117 Collections.emptyList());
119 final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
120 RestconfDataServiceConstant.ReadData.FIELDS,
121 Collections.emptyList());
123 // parameter can be in URI at most once
124 checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
125 checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
126 checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
127 checkParameterCount(fields, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
129 // check and set content
130 final String contentValue = content.get(0);
131 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
132 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
133 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
134 throw new RestconfDocumentedException(
135 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
136 "Invalid content parameter: " + contentValue, null,
137 "The content parameter value must be either config, nonconfig or all (default)"));
141 builder.setContent(content.get(0));
143 // check and set depth
144 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
145 final Integer value = Ints.tryParse(depth.get(0));
147 if (value == null || value < RestconfDataServiceConstant.ReadData.MIN_DEPTH
148 || value > RestconfDataServiceConstant.ReadData.MAX_DEPTH) {
149 throw new RestconfDocumentedException(
150 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
151 "Invalid depth parameter: " + depth, null,
152 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
154 builder.setDepth(value);
158 // check and set fields
159 if (!fields.isEmpty()) {
160 builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
163 // check and set withDefaults parameter
164 if (!withDefaults.isEmpty()) {
165 switch (withDefaults.get(0)) {
166 case RestconfDataServiceConstant.ReadData.REPORT_ALL_TAGGED_DEFAULT_VALUE:
167 builder.setTagged(true);
169 case RestconfDataServiceConstant.ReadData.REPORT_ALL_DEFAULT_VALUE:
172 builder.setWithDefault(withDefaults.get(0));
175 return builder.build();
179 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
180 * inside of object {@link RestconfStrategy} provided as a parameter.
182 * @param valueOfContent type of data to read (config, state, all)
183 * @param path the path to read
184 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
185 * @param withDefa value of with-defaults parameter
186 * @param ctx schema context
187 * @return {@link NormalizedNode}
189 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
190 final @NonNull YangInstanceIdentifier path,
191 final @NonNull RestconfStrategy strategy,
192 final String withDefa, final EffectiveModelContext ctx) {
193 switch (valueOfContent) {
194 case RestconfDataServiceConstant.ReadData.CONFIG:
195 if (withDefa == null) {
196 return readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true);
198 return prepareDataByParamWithDef(
199 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
200 path, withDefa, ctx);
202 case RestconfDataServiceConstant.ReadData.NONCONFIG:
203 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, true);
204 case RestconfDataServiceConstant.ReadData.ALL:
205 return readAllData(strategy, path, withDefa, ctx);
208 throw new RestconfDocumentedException(
209 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
210 "Invalid content parameter: " + valueOfContent, null,
211 "The content parameter value must be either config, nonconfig or all (default)"));
217 * Check if URI does not contain value for the same parameter more than once.
219 * @param parameterValues URI parameter values
220 * @param parameterName URI parameter name
223 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
224 if (parameterValues.size() > 1) {
225 throw new RestconfDocumentedException(
226 "Parameter " + parameterName + " can appear at most once in request URI",
227 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
232 * Check if URI does not contain not allowed parameters for specified operation.
234 * @param usedParameters parameters used in URI request
235 * @param allowedParameters allowed parameters for operation
238 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
239 final @NonNull String... allowedParameters) {
240 // FIXME: there should be a speedier way to do this
241 final Set<String> notAllowedParameters = Sets.newHashSet(usedParameters);
242 notAllowedParameters.removeAll(Sets.newHashSet(allowedParameters));
244 if (!notAllowedParameters.isEmpty()) {
245 throw new RestconfDocumentedException(
246 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
247 RestconfError.ErrorType.PROTOCOL,
248 RestconfError.ErrorTag.INVALID_VALUE);
252 private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
253 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
263 throw new RestconfDocumentedException("");
266 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
267 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
268 if (result instanceof ContainerNode) {
269 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
270 Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
271 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
272 return builder.build();
274 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
275 Builders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
276 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
277 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
278 return builder.build();
282 private static void buildMapEntryBuilder(
283 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
284 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
285 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
286 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
287 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
288 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
289 if (child instanceof ContainerNode) {
290 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
291 Builders.containerBuilder((ContainerSchemaNode) childSchema);
292 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
293 builder.withChild(childBuilder.build());
294 } else if (child instanceof MapNode) {
295 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
296 Builders.mapBuilder((ListSchemaNode) childSchema);
297 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
298 ((ListSchemaNode) childSchema).getKeyDefinition());
299 builder.withChild(childBuilder.build());
300 } else if (child instanceof LeafNode) {
301 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
302 final Object nodeVal = child.getValue();
303 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
304 Builders.leafBuilder((LeafSchemaNode) childSchema);
305 if (keys.contains(child.getNodeType())) {
306 leafBuilder.withValue(((LeafNode<?>) child).getValue());
307 builder.withChild(leafBuilder.build());
310 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
311 leafBuilder.withValue(((LeafNode<?>) child).getValue());
312 builder.withChild(leafBuilder.build());
315 if (defaultVal != null && defaultVal.equals(nodeVal)) {
316 leafBuilder.withValue(((LeafNode<?>) child).getValue());
317 builder.withChild(leafBuilder.build());
325 private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
326 final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
327 final List<QName> keys) {
328 for (final MapEntryNode mapEntryNode : result.getValue()) {
329 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
330 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
331 .getDataSchemaNode();
332 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
333 Builders.mapEntryBuilder((ListSchemaNode) childSchema);
334 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
335 builder.withChild(mapEntryBuilder.build());
339 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
340 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
341 final YangInstanceIdentifier actualPath, final boolean trim) {
342 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
343 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
344 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
345 if (child instanceof ContainerNode) {
346 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
347 Builders.containerBuilder((ContainerSchemaNode) childSchema);
348 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
349 builder.withChild(builderChild.build());
350 } else if (child instanceof MapNode) {
351 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
352 Builders.mapBuilder((ListSchemaNode) childSchema);
353 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
354 ((ListSchemaNode) childSchema).getKeyDefinition());
355 builder.withChild(childBuilder.build());
356 } else if (child instanceof LeafNode) {
357 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
358 final Object nodeVal = child.getValue();
359 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
360 Builders.leafBuilder((LeafSchemaNode) childSchema);
362 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
363 leafBuilder.withValue(((LeafNode<?>) child).getValue());
364 builder.withChild(leafBuilder.build());
367 if (defaultVal != null && defaultVal.equals(nodeVal)) {
368 leafBuilder.withValue(((LeafNode<?>) child).getValue());
369 builder.withChild(leafBuilder.build());
377 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
378 * If don't, we have to read all data from DS (state + config)
380 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
381 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
382 * in {@link RestconfStrategy} if any
383 * @return {@link NormalizedNode}
385 static @Nullable NormalizedNode<?, ?> readDataViaTransaction(final @NonNull RestconfStrategy strategy,
386 final LogicalDatastoreType store, final YangInstanceIdentifier path,
387 final boolean closeTransactionChain) {
388 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
389 final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = strategy.read(store, path);
390 if (closeTransactionChain) {
391 //Method close transactionChain if any
392 FutureCallbackTx.addCallback(listenableFuture, READ_TYPE_TX, dataFactory, strategy.getTransactionChain());
394 FutureCallbackTx.addCallback(listenableFuture, READ_TYPE_TX, dataFactory);
396 return dataFactory.build();
400 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
401 * {@link RestconfStrategy} provided as a parameter if any.
403 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
404 * @param withDefa with-defaults parameter
405 * @param ctx schema context
406 * @return {@link NormalizedNode}
408 private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull RestconfStrategy strategy,
409 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
410 // PREPARE STATE DATA NODE
411 final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(
412 strategy, LogicalDatastoreType.OPERATIONAL, path, false);
414 // PREPARE CONFIG DATA NODE
415 final NormalizedNode<?, ?> configDataNode;
416 //Here will be closed transactionChain if any
417 if (withDefa == null) {
418 configDataNode = readDataViaTransaction(
419 strategy, LogicalDatastoreType.CONFIGURATION, path, true);
421 configDataNode = prepareDataByParamWithDef(
422 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
423 path, withDefa, ctx);
427 if (stateDataNode == null && configDataNode == null) {
431 // return config data
432 if (stateDataNode == null) {
433 return configDataNode;
437 if (configDataNode == null) {
438 return stateDataNode;
441 // merge data from config and state
442 return mergeStateAndConfigData(stateDataNode, configDataNode);
446 * Merge state and config data into a single NormalizedNode.
448 * @param stateDataNode data node of state data
449 * @param configDataNode data node of config data
450 * @return {@link NormalizedNode}
452 private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
453 final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
454 validateNodeMerge(stateDataNode, configDataNode);
455 if (configDataNode instanceof RpcDefinition) {
456 return prepareRpcData(configDataNode, stateDataNode);
458 return prepareData(configDataNode, stateDataNode);
463 * Validates whether the two NormalizedNodes can be merged.
465 * @param stateDataNode data node of state data
466 * @param configDataNode data node of config data
468 private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
469 final @NonNull NormalizedNode<?, ?> configDataNode) {
470 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
471 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
472 if (!moduleOfStateData.equals(moduleOfConfigData)) {
473 throw new RestconfDocumentedException("Unable to merge data from different modules.");
478 * Prepare and map data for rpc.
480 * @param configDataNode data node of config data
481 * @param stateDataNode data node of state data
482 * @return {@link NormalizedNode}
484 private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
485 final @NonNull NormalizedNode<?, ?> stateDataNode) {
486 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
488 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
491 mapRpcDataNode(configDataNode, mapEntryBuilder);
493 mapRpcDataNode(stateDataNode, mapEntryBuilder);
495 return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
499 * Map node to map entry builder.
501 * @param dataNode data node
502 * @param mapEntryBuilder builder for mapping data
504 private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
505 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
506 ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
510 * Prepare and map all data from DS.
512 * @param configDataNode data node of config data
513 * @param stateDataNode data node of state data
514 * @return {@link NormalizedNode}
516 @SuppressWarnings("unchecked")
517 private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
518 final @NonNull NormalizedNode<?, ?> stateDataNode) {
519 if (configDataNode instanceof OrderedMapNode) {
520 final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
521 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
524 ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
526 return builder.build();
527 } else if (configDataNode instanceof MapNode) {
528 final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
529 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
532 ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
534 return builder.build();
535 } else if (configDataNode instanceof MapEntryNode) {
536 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
537 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
540 ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
542 return builder.build();
543 } else if (configDataNode instanceof ContainerNode) {
544 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
545 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
548 ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
550 return builder.build();
551 } else if (configDataNode instanceof AugmentationNode) {
552 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
553 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
555 mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
556 ((AugmentationNode) stateDataNode).getValue(), builder);
558 return builder.build();
559 } else if (configDataNode instanceof ChoiceNode) {
560 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
561 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
564 ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
566 return builder.build();
567 } else if (configDataNode instanceof LeafNode) {
568 return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
569 } else if (configDataNode instanceof OrderedLeafSetNode) {
570 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
571 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
573 mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
574 ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
575 return builder.build();
576 } else if (configDataNode instanceof LeafSetNode) {
577 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
578 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
580 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
581 ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
582 return builder.build();
583 } else if (configDataNode instanceof LeafSetEntryNode) {
584 return Builders.leafSetEntryBuilder()
585 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
586 .withValue(configDataNode.getValue())
588 } else if (configDataNode instanceof UnkeyedListNode) {
589 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
590 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
592 mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
593 ((UnkeyedListNode) stateDataNode).getValue(), builder);
594 return builder.build();
595 } else if (configDataNode instanceof UnkeyedListEntryNode) {
596 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
597 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
599 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
600 ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
601 return builder.build();
603 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
608 * Map value from container node to builder.
610 * @param configData collection of config data nodes
611 * @param stateData collection of state data nodes
612 * @param builder builder
614 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
615 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
616 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
617 final Map<PathArgument, T> configMap = configData.stream().collect(
618 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
619 final Map<PathArgument, T> stateMap = stateData.stream().collect(
620 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
622 // merge config and state data of children with different identifiers
623 mapDataToBuilder(configMap, stateMap, builder);
625 // merge config and state data of children with the same identifiers
626 mergeDataToBuilder(configMap, stateMap, builder);
630 * Map data with different identifiers to builder. Data with different identifiers can be just added
631 * as childs to parent node.
633 * @param configMap map of config data nodes
634 * @param stateMap map of state data nodes
635 * @param builder - builder
637 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
638 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
639 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
640 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
641 y -> builder.addChild(y.getValue()));
642 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
643 y -> builder.addChild(y.getValue()));
647 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
648 * go one level down with {@code prepareData} method.
650 * @param configMap immutable config data
651 * @param stateMap immutable state data
652 * @param builder - builder
654 @SuppressWarnings("unchecked")
655 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
656 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
657 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
658 // it is enough to process only config data because operational contains the same data
659 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
660 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));