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.utils.parser.ParserFieldsParameter.parseFieldsParameter;
11 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter.parseFieldsPaths;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Collection;
17 import java.util.List;
19 import java.util.Optional;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
23 import javax.ws.rs.core.MultivaluedMap;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError;
32 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
33 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.RestconfStrategy;
34 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfDataServiceConstant.ReadData.WithDefaults;
35 import org.opendaylight.yangtools.yang.common.ErrorTag;
36 import org.opendaylight.yangtools.yang.common.ErrorType;
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.SystemLeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
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.api.schema.UserLeafSetNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.api.schema.builder.ListNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
66 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
67 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
68 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
69 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
77 * Util class for read data from data store via transaction.
81 * <li>all (config + state)
84 public final class ReadDataTransactionUtil {
85 private static final Set<String> ALLOWED_PARAMETERS = Set.of(
86 RestconfDataServiceConstant.ReadData.CONTENT,
87 RestconfDataServiceConstant.ReadData.DEPTH,
88 RestconfDataServiceConstant.ReadData.FIELDS,
89 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
90 private static final List<String> DEFAULT_CONTENT = List.of(RestconfDataServiceConstant.ReadData.ALL);
91 private static final List<String> DEFAULT_DEPTH = List.of(RestconfDataServiceConstant.ReadData.UNBOUNDED);
92 private static final String READ_TYPE_TX = "READ";
94 private ReadDataTransactionUtil() {
99 * Parse parameters from URI request and check their types and values.
101 * @param identifier {@link InstanceIdentifierContext}
102 * @param uriInfo URI info
103 * @return {@link QueryParameters}
105 public static QueryParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
106 final UriInfo uriInfo) {
107 final QueryParameters.Builder builder = QueryParameters.builder();
108 if (uriInfo == null) {
109 return builder.build();
112 // check only allowed parameters
113 final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
114 checkParametersTypes(queryParams.keySet(), ALLOWED_PARAMETERS);
116 // read parameters from URI or set default values
117 final List<String> content = queryParams.getOrDefault(
118 RestconfDataServiceConstant.ReadData.CONTENT, DEFAULT_CONTENT);
119 final List<String> depth = queryParams.getOrDefault(
120 RestconfDataServiceConstant.ReadData.DEPTH, DEFAULT_DEPTH);
121 final List<String> withDefaults = queryParams.getOrDefault(
122 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS, List.of());
124 final List<String> fields = queryParams.getOrDefault(RestconfDataServiceConstant.ReadData.FIELDS, List.of());
126 // parameter can be in URI at most once
127 checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
128 checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
129 checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
130 checkParameterCount(withDefaults, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
132 // check and set content
133 final String contentValue = content.get(0);
134 switch (contentValue) {
135 case RestconfDataServiceConstant.ReadData.ALL:
136 case RestconfDataServiceConstant.ReadData.CONFIG:
137 case RestconfDataServiceConstant.ReadData.NONCONFIG:
138 // FIXME: we really want to have a proper enumeration for this field
139 builder.setContent(contentValue);
142 throw new RestconfDocumentedException(
143 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
144 "Invalid content parameter: " + contentValue, null,
145 "The content parameter value must be either config, nonconfig or all (default)"));
148 // check and set depth
149 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
150 final Integer value = Ints.tryParse(depth.get(0));
152 if (value == null || value < RestconfDataServiceConstant.ReadData.MIN_DEPTH
153 || value > RestconfDataServiceConstant.ReadData.MAX_DEPTH) {
154 throw new RestconfDocumentedException(
155 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
156 "Invalid depth parameter: " + depth, null,
157 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
159 builder.setDepth(value);
163 // check and set fields
164 if (!fields.isEmpty()) {
165 if (identifier.getMountPoint() != null) {
166 builder.setFieldPaths(parseFieldsPaths(identifier, fields.get(0)));
168 builder.setFields(parseFieldsParameter(identifier, fields.get(0)));
172 // check and set withDefaults parameter
173 if (!withDefaults.isEmpty()) {
174 final String str = withDefaults.get(0);
175 final WithDefaults val = WithDefaults.forValue(str);
177 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
178 "Invalid with-defaults parameter: " + str, null,
179 "The with-defaults parameter must be a string in " + WithDefaults.possibleValues()));
185 case REPORT_ALL_TAGGED:
186 builder.setTagged(true);
189 builder.setWithDefault(val.value());
192 return builder.build();
196 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
197 * inside of object {@link RestconfStrategy} provided as a parameter.
199 * @param valueOfContent type of data to read (config, state, all)
200 * @param path the path to read
201 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
202 * @param withDefa value of with-defaults parameter
203 * @param ctx schema context
204 * @return {@link NormalizedNode}
206 public static @Nullable NormalizedNode readData(final @NonNull String valueOfContent,
207 final @NonNull YangInstanceIdentifier path,
208 final @NonNull RestconfStrategy strategy,
209 final String withDefa, final EffectiveModelContext ctx) {
210 switch (valueOfContent) {
211 case RestconfDataServiceConstant.ReadData.CONFIG:
212 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path);
213 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
214 case RestconfDataServiceConstant.ReadData.NONCONFIG:
215 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
216 case RestconfDataServiceConstant.ReadData.ALL:
217 return readAllData(strategy, path, withDefa, ctx);
219 throw new RestconfDocumentedException(
220 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
221 "Invalid content parameter: " + valueOfContent, null,
222 "The content parameter value must be either config, nonconfig or all (default)"));
227 * Read specific type of data from data store via transaction with specified subtrees that should only be read.
228 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
230 * @param valueOfContent type of data to read (config, state, all)
231 * @param path the parent path to read
232 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
233 * @param withDefa value of with-defaults parameter
234 * @param ctx schema context
235 * @param fields paths to selected subtrees which should be read, relative to to the parent path
236 * @return {@link NormalizedNode}
238 public static @Nullable NormalizedNode readData(final @NonNull String valueOfContent,
239 final @NonNull YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
240 final @Nullable String withDefa, @NonNull final EffectiveModelContext ctx,
241 final @NonNull List<YangInstanceIdentifier> fields) {
242 switch (valueOfContent) {
243 case RestconfDataServiceConstant.ReadData.CONFIG:
244 final NormalizedNode read = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
246 return withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa, ctx);
247 case RestconfDataServiceConstant.ReadData.NONCONFIG:
248 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, fields);
249 case RestconfDataServiceConstant.ReadData.ALL:
250 return readAllData(strategy, path, withDefa, ctx, fields);
252 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
253 "Invalid content parameter: " + valueOfContent, null,
254 "The content parameter value must be either config, nonconfig or all (default)"));
259 * Check if URI does not contain value for the same parameter more than once.
261 * @param parameterValues URI parameter values
262 * @param parameterName URI parameter name
265 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
266 if (parameterValues.size() > 1) {
267 throw new RestconfDocumentedException(
268 "Parameter " + parameterName + " can appear at most once in request URI",
269 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
274 * Check if URI does not contain not allowed parameters for specified operation.
276 * @param usedParameters parameters used in URI request
277 * @param allowedParameters allowed parameters for operation
280 static void checkParametersTypes(final @NonNull Set<String> usedParameters,
281 final @NonNull Set<String> allowedParameters) {
282 if (!allowedParameters.containsAll(usedParameters)) {
283 final Set<String> notAllowedParameters = usedParameters.stream()
284 .filter(param -> !allowedParameters.contains(param))
285 .collect(Collectors.toSet());
286 throw new RestconfDocumentedException(
287 "Not allowed parameters for " + READ_TYPE_TX + " operation: " + notAllowedParameters,
288 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
292 private static NormalizedNode prepareDataByParamWithDef(final NormalizedNode result,
293 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
303 throw new RestconfDocumentedException("");
306 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
307 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
308 if (result instanceof ContainerNode) {
309 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
310 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
311 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
312 return builder.build();
314 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
315 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
316 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
317 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
318 return builder.build();
322 private static void buildMapEntryBuilder(
323 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
324 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
325 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
326 for (final DataContainerChild child : result.body()) {
327 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
328 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
329 if (child instanceof ContainerNode) {
330 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
331 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
332 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
333 builder.withChild(childBuilder.build());
334 } else if (child instanceof MapNode) {
335 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
336 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
337 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
338 ((ListSchemaNode) childSchema).getKeyDefinition());
339 builder.withChild(childBuilder.build());
340 } else if (child instanceof LeafNode) {
341 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
342 final Object nodeVal = child.body();
343 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
344 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
345 if (keys.contains(child.getIdentifier().getNodeType())) {
346 leafBuilder.withValue(((LeafNode<?>) child).body());
347 builder.withChild(leafBuilder.build());
350 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
351 leafBuilder.withValue(((LeafNode<?>) child).body());
352 builder.withChild(leafBuilder.build());
355 if (defaultVal != null && defaultVal.equals(nodeVal)) {
356 leafBuilder.withValue(((LeafNode<?>) child).body());
357 builder.withChild(leafBuilder.build());
365 private static void buildList(final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder,
366 final MapNode result, final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path,
367 final boolean trim, final List<QName> keys) {
368 for (final MapEntryNode mapEntryNode : result.body()) {
369 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
370 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(actualNode).orElseThrow()
371 .getDataSchemaNode();
372 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
373 SchemaAwareBuilders.mapEntryBuilder((ListSchemaNode) childSchema);
374 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
375 builder.withChild(mapEntryBuilder.build());
379 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
380 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
381 final YangInstanceIdentifier actualPath, final boolean trim) {
382 for (final DataContainerChild child : result.body()) {
383 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
384 final DataSchemaNode childSchema = baseSchemaCtxTree.findChild(path).orElseThrow().getDataSchemaNode();
385 if (child instanceof ContainerNode) {
386 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
387 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) childSchema);
388 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
389 builder.withChild(builderChild.build());
390 } else if (child instanceof MapNode) {
391 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> childBuilder =
392 SchemaAwareBuilders.mapBuilder((ListSchemaNode) childSchema);
393 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
394 ((ListSchemaNode) childSchema).getKeyDefinition());
395 builder.withChild(childBuilder.build());
396 } else if (child instanceof LeafNode) {
397 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
398 final Object nodeVal = child.body();
399 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
400 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) childSchema);
402 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
403 leafBuilder.withValue(((LeafNode<?>) child).body());
404 builder.withChild(leafBuilder.build());
407 if (defaultVal != null && defaultVal.equals(nodeVal)) {
408 leafBuilder.withValue(((LeafNode<?>) child).body());
409 builder.withChild(leafBuilder.build());
417 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
418 * If don't, we have to read all data from DS (state + config)
420 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
421 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
422 * in {@link RestconfStrategy} if any
423 * @return {@link NormalizedNode}
425 static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
426 final LogicalDatastoreType store, final YangInstanceIdentifier path) {
427 return extractReadData(strategy, path, strategy.read(store, path));
431 * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
432 * specified subtrees that should only be read.
434 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
435 * @param store datastore type
436 * @param path parent path to selected fields
437 * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
438 * in {@link RestconfStrategy} if any
439 * @param fields paths to selected subtrees which should be read, relative to to the parent path
440 * @return {@link NormalizedNode}
442 private static @Nullable NormalizedNode readDataViaTransaction(final @NonNull RestconfStrategy strategy,
443 final @NonNull LogicalDatastoreType store, final @NonNull YangInstanceIdentifier path,
444 final @NonNull List<YangInstanceIdentifier> fields) {
445 return extractReadData(strategy, path, strategy.read(store, path, fields));
448 private static NormalizedNode extractReadData(final RestconfStrategy strategy,
449 final YangInstanceIdentifier path, final ListenableFuture<Optional<NormalizedNode>> dataFuture) {
450 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
451 FutureCallbackTx.addCallback(dataFuture, READ_TYPE_TX, dataFactory, path);
452 return dataFactory.build();
456 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
457 * {@link RestconfStrategy} provided as a parameter if any.
459 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
460 * @param withDefa with-defaults parameter
461 * @param ctx schema context
462 * @return {@link NormalizedNode}
464 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
465 final YangInstanceIdentifier path, final String withDefa, final EffectiveModelContext ctx) {
466 // PREPARE STATE DATA NODE
467 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path);
468 // PREPARE CONFIG DATA NODE
469 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION,
472 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
473 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
477 * Read config and state data with selected subtrees that should only be read, then map them.
478 * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
480 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
481 * @param path parent path to selected fields
482 * @param withDefa with-defaults parameter
483 * @param ctx schema context
484 * @param fields paths to selected subtrees which should be read, relative to to the parent path
485 * @return {@link NormalizedNode}
487 private static @Nullable NormalizedNode readAllData(final @NonNull RestconfStrategy strategy,
488 final @NonNull YangInstanceIdentifier path, final @Nullable String withDefa,
489 final @NonNull EffectiveModelContext ctx, final @NonNull List<YangInstanceIdentifier> fields) {
490 // PREPARE STATE DATA NODE
491 final NormalizedNode stateDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path,
494 // PREPARE CONFIG DATA NODE
495 final NormalizedNode configDataNode = readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path,
497 return mergeConfigAndSTateDataIfNeeded(stateDataNode,
498 withDefa == null ? configDataNode : prepareDataByParamWithDef(configDataNode, path, withDefa, ctx));
501 private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
502 final NormalizedNode configDataNode) {
504 if (stateDataNode == null && configDataNode == null) {
508 // return config data
509 if (stateDataNode == null) {
510 return configDataNode;
514 if (configDataNode == null) {
515 return stateDataNode;
518 // merge data from config and state
519 return mergeStateAndConfigData(stateDataNode, configDataNode);
523 * Merge state and config data into a single NormalizedNode.
525 * @param stateDataNode data node of state data
526 * @param configDataNode data node of config data
527 * @return {@link NormalizedNode}
529 private static @NonNull NormalizedNode mergeStateAndConfigData(
530 final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
531 validateNodeMerge(stateDataNode, configDataNode);
532 if (configDataNode instanceof RpcDefinition) {
533 return prepareRpcData(configDataNode, stateDataNode);
535 return prepareData(configDataNode, stateDataNode);
540 * Validates whether the two NormalizedNodes can be merged.
542 * @param stateDataNode data node of state data
543 * @param configDataNode data node of config data
545 private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
546 final @NonNull NormalizedNode configDataNode) {
547 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
548 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
549 if (!moduleOfStateData.equals(moduleOfConfigData)) {
550 throw new RestconfDocumentedException("Unable to merge data from different modules.");
555 * Prepare and map data for rpc.
557 * @param configDataNode data node of config data
558 * @param stateDataNode data node of state data
559 * @return {@link NormalizedNode}
561 private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
562 final @NonNull NormalizedNode stateDataNode) {
563 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
565 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
568 mapRpcDataNode(configDataNode, mapEntryBuilder);
570 mapRpcDataNode(stateDataNode, mapEntryBuilder);
572 return ImmutableNodes.mapNodeBuilder(configDataNode.getIdentifier().getNodeType())
573 .addChild(mapEntryBuilder.build())
578 * Map node to map entry builder.
580 * @param dataNode data node
581 * @param mapEntryBuilder builder for mapping data
583 private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
584 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
585 ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
589 * Prepare and map all data from DS.
591 * @param configDataNode data node of config data
592 * @param stateDataNode data node of state data
593 * @return {@link NormalizedNode}
595 @SuppressWarnings("unchecked")
596 private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
597 final @NonNull NormalizedNode stateDataNode) {
598 if (configDataNode instanceof UserMapNode) {
599 final CollectionNodeBuilder<MapEntryNode, UserMapNode> builder = Builders
600 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
603 ((UserMapNode) configDataNode).body(), ((UserMapNode) stateDataNode).body(), builder);
605 return builder.build();
606 } else if (configDataNode instanceof MapNode) {
607 final CollectionNodeBuilder<MapEntryNode, SystemMapNode> builder = ImmutableNodes
608 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
611 ((MapNode) configDataNode).body(), ((MapNode) stateDataNode).body(), builder);
613 return builder.build();
614 } else if (configDataNode instanceof MapEntryNode) {
615 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
616 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
619 ((MapEntryNode) configDataNode).body(), ((MapEntryNode) stateDataNode).body(), builder);
621 return builder.build();
622 } else if (configDataNode instanceof ContainerNode) {
623 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
624 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
627 ((ContainerNode) configDataNode).body(), ((ContainerNode) stateDataNode).body(), builder);
629 return builder.build();
630 } else if (configDataNode instanceof AugmentationNode) {
631 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
632 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
634 mapValueToBuilder(((AugmentationNode) configDataNode).body(),
635 ((AugmentationNode) stateDataNode).body(), builder);
637 return builder.build();
638 } else if (configDataNode instanceof ChoiceNode) {
639 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
640 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
643 ((ChoiceNode) configDataNode).body(), ((ChoiceNode) stateDataNode).body(), builder);
645 return builder.build();
646 } else if (configDataNode instanceof LeafNode) {
647 return ImmutableNodes.leafNode(configDataNode.getIdentifier().getNodeType(), configDataNode.body());
648 } else if (configDataNode instanceof UserLeafSetNode) {
649 final ListNodeBuilder<Object, UserLeafSetNode<Object>> builder = Builders
650 .orderedLeafSetBuilder().withNodeIdentifier(((UserLeafSetNode<?>) configDataNode).getIdentifier());
652 mapValueToBuilder(((UserLeafSetNode<Object>) configDataNode).body(),
653 ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
654 return builder.build();
655 } else if (configDataNode instanceof LeafSetNode) {
656 final ListNodeBuilder<Object, SystemLeafSetNode<Object>> builder = Builders
657 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
659 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).body(),
660 ((LeafSetNode<Object>) stateDataNode).body(), builder);
661 return builder.build();
662 } else if (configDataNode instanceof LeafSetEntryNode) {
663 return Builders.leafSetEntryBuilder()
664 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
665 .withValue(configDataNode.body())
667 } else if (configDataNode instanceof UnkeyedListNode) {
668 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
669 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
671 mapValueToBuilder(((UnkeyedListNode) configDataNode).body(),
672 ((UnkeyedListNode) stateDataNode).body(), builder);
673 return builder.build();
674 } else if (configDataNode instanceof UnkeyedListEntryNode) {
675 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
676 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
678 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).body(),
679 ((UnkeyedListEntryNode) stateDataNode).body(), builder);
680 return builder.build();
682 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
687 * Map value from container node to builder.
689 * @param configData collection of config data nodes
690 * @param stateData collection of state data nodes
691 * @param builder builder
693 private static <T extends NormalizedNode> void mapValueToBuilder(
694 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
695 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
696 final Map<PathArgument, T> configMap = configData.stream().collect(
697 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
698 final Map<PathArgument, T> stateMap = stateData.stream().collect(
699 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
701 // merge config and state data of children with different identifiers
702 mapDataToBuilder(configMap, stateMap, builder);
704 // merge config and state data of children with the same identifiers
705 mergeDataToBuilder(configMap, stateMap, builder);
709 * Map data with different identifiers to builder. Data with different identifiers can be just added
710 * as childs to parent node.
712 * @param configMap map of config data nodes
713 * @param stateMap map of state data nodes
714 * @param builder - builder
716 private static <T extends NormalizedNode> void mapDataToBuilder(
717 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
718 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
719 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
720 y -> builder.addChild(y.getValue()));
721 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
722 y -> builder.addChild(y.getValue()));
726 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
727 * go one level down with {@code prepareData} method.
729 * @param configMap immutable config data
730 * @param stateMap immutable state data
731 * @param builder - builder
733 @SuppressWarnings("unchecked")
734 private static <T extends NormalizedNode> void mergeDataToBuilder(
735 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
736 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
737 // it is enough to process only config data because operational contains the same data
738 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
739 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));