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.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 * Util class for read data from data store via transaction.
77 * <li>all (config + state)
81 public final class ReadDataTransactionUtil {
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(RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
104 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 switch (withDefaults.get(0)) {
167 case RestconfDataServiceConstant.ReadData.REPORT_ALL_TAGGED_DEFAULT_VALUE:
168 builder.setTagged(true);
170 case RestconfDataServiceConstant.ReadData.REPORT_ALL_DEFAULT_VALUE:
173 builder.setWithDefault(withDefaults.get(0));
176 return builder.build();
180 * Read specific type of data from data store via transaction.
182 * @param valueOfContent type of data to read (config, state, all)
183 * @param strategy {@link RestconfStrategy} - wrapper for variables
184 * @param schemaContext schema context
185 * @return {@link NormalizedNode}
187 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
188 final YangInstanceIdentifier path, final @NonNull RestconfStrategy strategy,
189 final SchemaContext schemaContext) {
190 return readData(valueOfContent, path, strategy, null, schemaContext);
194 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
195 * inside of object {@link RestconfStrategy} provided as a parameter.
197 * @param valueOfContent type of data to read (config, state, all)
198 * @param path the path to read
199 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
200 * @param withDefa valee of with-defaults parameter
201 * @param ctx schema context
202 * @return {@link NormalizedNode}
204 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
205 final @NonNull YangInstanceIdentifier path,
206 final @NonNull RestconfStrategy strategy,
207 final String withDefa, final SchemaContext ctx) {
208 switch (valueOfContent) {
209 case RestconfDataServiceConstant.ReadData.CONFIG:
210 if (withDefa == null) {
211 return readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true);
213 return prepareDataByParamWithDef(
214 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
215 path, withDefa, ctx);
217 case RestconfDataServiceConstant.ReadData.NONCONFIG:
218 return readDataViaTransaction(strategy, LogicalDatastoreType.OPERATIONAL, path, true);
219 case RestconfDataServiceConstant.ReadData.ALL:
220 return readAllData(strategy, path, withDefa, ctx);
223 throw new RestconfDocumentedException(
224 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
225 "Invalid content parameter: " + valueOfContent, null,
226 "The content parameter value must be either config, nonconfig or all (default)"));
232 * Check if URI does not contain value for the same parameter more than once.
234 * @param parameterValues URI parameter values
235 * @param parameterName URI parameter name
238 static void checkParameterCount(final @NonNull List<String> parameterValues, final @NonNull String parameterName) {
239 if (parameterValues.size() > 1) {
240 throw new RestconfDocumentedException(
241 "Parameter " + parameterName + " can appear at most once in request URI",
242 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
247 * Check if URI does not contain not allowed parameters for specified operation.
249 * @param operationType type of operation (READ, POST, PUT, DELETE...)
250 * @param usedParameters parameters used in URI request
251 * @param allowedParameters allowed parameters for operation
254 static void checkParametersTypes(final @NonNull String operationType,
255 final @NonNull Set<String> usedParameters,
256 final @NonNull String... allowedParameters) {
257 // FIXME: there should be a speedier way to do this
258 final Set<String> notAllowedParameters = Sets.newHashSet(usedParameters);
259 notAllowedParameters.removeAll(Sets.newHashSet(allowedParameters));
261 if (!notAllowedParameters.isEmpty()) {
262 throw new RestconfDocumentedException(
263 "Not allowed parameters for " + operationType + " operation: " + notAllowedParameters,
264 RestconfError.ErrorType.PROTOCOL,
265 RestconfError.ErrorTag.INVALID_VALUE);
269 private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
270 final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
280 throw new RestconfDocumentedException("");
283 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
284 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
285 if (result instanceof ContainerNode) {
286 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
287 Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
288 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
289 return builder.build();
291 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
292 Builders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
293 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
294 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
295 return builder.build();
299 private static void buildMapEntryBuilder(
300 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
301 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
302 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
303 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
304 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
305 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
306 if (child instanceof ContainerNode) {
307 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
308 Builders.containerBuilder((ContainerSchemaNode) childSchema);
309 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
310 builder.withChild(childBuilder.build());
311 } else if (child instanceof MapNode) {
312 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
313 Builders.mapBuilder((ListSchemaNode) childSchema);
314 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
315 ((ListSchemaNode) childSchema).getKeyDefinition());
316 builder.withChild(childBuilder.build());
317 } else if (child instanceof LeafNode) {
318 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
319 final Object nodeVal = child.getValue();
320 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
321 Builders.leafBuilder((LeafSchemaNode) childSchema);
322 if (keys.contains(child.getNodeType())) {
323 leafBuilder.withValue(((LeafNode<?>) child).getValue());
324 builder.withChild(leafBuilder.build());
327 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
328 leafBuilder.withValue(((LeafNode<?>) child).getValue());
329 builder.withChild(leafBuilder.build());
332 if (defaultVal != null && defaultVal.equals(nodeVal)) {
333 leafBuilder.withValue(((LeafNode<?>) child).getValue());
334 builder.withChild(leafBuilder.build());
342 private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
343 final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
344 final List<QName> keys) {
345 for (final MapEntryNode mapEntryNode : result.getValue()) {
346 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
347 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(actualNode).getDataSchemaNode();
348 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
349 Builders.mapEntryBuilder((ListSchemaNode) childSchema);
350 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
351 builder.withChild(mapEntryBuilder.build());
355 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
356 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
357 final YangInstanceIdentifier actualPath, final boolean trim) {
358 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
359 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
360 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
361 if (child instanceof ContainerNode) {
362 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
363 Builders.containerBuilder((ContainerSchemaNode) childSchema);
364 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
365 builder.withChild(builderChild.build());
366 } else if (child instanceof MapNode) {
367 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
368 Builders.mapBuilder((ListSchemaNode) childSchema);
369 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
370 ((ListSchemaNode) childSchema).getKeyDefinition());
371 builder.withChild(childBuilder.build());
372 } else if (child instanceof LeafNode) {
373 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
374 final Object nodeVal = child.getValue();
375 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
376 Builders.leafBuilder((LeafSchemaNode) childSchema);
378 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
379 leafBuilder.withValue(((LeafNode<?>) child).getValue());
380 builder.withChild(leafBuilder.build());
383 if (defaultVal != null && defaultVal.equals(nodeVal)) {
384 leafBuilder.withValue(((LeafNode<?>) child).getValue());
385 builder.withChild(leafBuilder.build());
393 * If is set specific {@link LogicalDatastoreType} in {@link RestconfStrategy}, then read this type of data from DS.
394 * If don't, we have to read all data from DS (state + config)
396 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
397 * @param closeTransactionChain If is set to true, after transaction it will close transactionChain
398 * in {@link RestconfStrategy} if any
399 * @return {@link NormalizedNode}
401 private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
402 final @NonNull RestconfStrategy strategy,
403 final LogicalDatastoreType store, final YangInstanceIdentifier path,
404 final boolean closeTransactionChain) {
405 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
406 final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = strategy.read(store, path);
407 if (closeTransactionChain) {
408 //Method close transactionChain if any
409 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
410 dataFactory, strategy.getTransactionChain());
412 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
415 return dataFactory.build();
419 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
420 * {@link RestconfStrategy} provided as a parameter if any.
422 * @param strategy {@link RestconfStrategy} - object that perform the actual DS operations
423 * @param withDefa with-defaults parameter
424 * @param ctx schema context
425 * @return {@link NormalizedNode}
427 private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull RestconfStrategy strategy,
428 final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
429 // PREPARE STATE DATA NODE
430 final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(
431 strategy, LogicalDatastoreType.OPERATIONAL, path, false);
433 // PREPARE CONFIG DATA NODE
434 final NormalizedNode<?, ?> configDataNode;
435 //Here will be closed transactionChain if any
436 if (withDefa == null) {
437 configDataNode = readDataViaTransaction(
438 strategy, LogicalDatastoreType.CONFIGURATION, path, true);
440 configDataNode = prepareDataByParamWithDef(
441 readDataViaTransaction(strategy, LogicalDatastoreType.CONFIGURATION, path, true),
442 path, withDefa, ctx);
446 if (stateDataNode == null && configDataNode == null) {
450 // return config data
451 if (stateDataNode == null) {
452 return configDataNode;
456 if (configDataNode == null) {
457 return stateDataNode;
460 // merge data from config and state
461 return mergeStateAndConfigData(stateDataNode, configDataNode);
465 * Merge state and config data into a single NormalizedNode.
467 * @param stateDataNode data node of state data
468 * @param configDataNode data node of config data
469 * @return {@link NormalizedNode}
471 private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
472 final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
473 validateNodeMerge(stateDataNode, configDataNode);
474 if (configDataNode instanceof RpcDefinition) {
475 return prepareRpcData(configDataNode, stateDataNode);
477 return prepareData(configDataNode, stateDataNode);
482 * Validates whether the two NormalizedNodes can be merged.
484 * @param stateDataNode data node of state data
485 * @param configDataNode data node of config data
487 private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
488 final @NonNull NormalizedNode<?, ?> configDataNode) {
489 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
490 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
491 if (!moduleOfStateData.equals(moduleOfConfigData)) {
492 throw new RestconfDocumentedException("Unable to merge data from different modules.");
497 * Prepare and map data for rpc.
499 * @param configDataNode data node of config data
500 * @param stateDataNode data node of state data
501 * @return {@link NormalizedNode}
503 private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
504 final @NonNull NormalizedNode<?, ?> stateDataNode) {
505 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
507 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
510 mapRpcDataNode(configDataNode, mapEntryBuilder);
512 mapRpcDataNode(stateDataNode, mapEntryBuilder);
514 return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
518 * Map node to map entry builder.
520 * @param dataNode data node
521 * @param mapEntryBuilder builder for mapping data
523 private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
524 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
525 ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
529 * Prepare and map all data from DS.
531 * @param configDataNode data node of config data
532 * @param stateDataNode data node of state data
533 * @return {@link NormalizedNode}
535 @SuppressWarnings("unchecked")
536 private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
537 final @NonNull NormalizedNode<?, ?> stateDataNode) {
538 if (configDataNode instanceof OrderedMapNode) {
539 final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
540 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
543 ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
545 return builder.build();
546 } else if (configDataNode instanceof MapNode) {
547 final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
548 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
551 ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
553 return builder.build();
554 } else if (configDataNode instanceof MapEntryNode) {
555 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
556 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
559 ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
561 return builder.build();
562 } else if (configDataNode instanceof ContainerNode) {
563 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
564 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
567 ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
569 return builder.build();
570 } else if (configDataNode instanceof AugmentationNode) {
571 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
572 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
574 mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
575 ((AugmentationNode) stateDataNode).getValue(), builder);
577 return builder.build();
578 } else if (configDataNode instanceof ChoiceNode) {
579 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
580 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
583 ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
585 return builder.build();
586 } else if (configDataNode instanceof LeafNode) {
587 return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
588 } else if (configDataNode instanceof OrderedLeafSetNode) {
589 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
590 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
592 mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
593 ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
594 return builder.build();
595 } else if (configDataNode instanceof LeafSetNode) {
596 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
597 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
599 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
600 ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
601 return builder.build();
602 } else if (configDataNode instanceof LeafSetEntryNode) {
603 return Builders.leafSetEntryBuilder()
604 .withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode).getIdentifier())
605 .withValue(configDataNode.getValue())
607 } else if (configDataNode instanceof UnkeyedListNode) {
608 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
609 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
611 mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
612 ((UnkeyedListNode) stateDataNode).getValue(), builder);
613 return builder.build();
614 } else if (configDataNode instanceof UnkeyedListEntryNode) {
615 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
616 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
618 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
619 ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
620 return builder.build();
622 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
627 * Map value from container node to builder.
629 * @param configData collection of config data nodes
630 * @param stateData collection of state data nodes
631 * @param builder builder
633 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
634 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
635 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
636 final Map<PathArgument, T> configMap = configData.stream().collect(
637 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
638 final Map<PathArgument, T> stateMap = stateData.stream().collect(
639 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
641 // merge config and state data of children with different identifiers
642 mapDataToBuilder(configMap, stateMap, builder);
644 // merge config and state data of children with the same identifiers
645 mergeDataToBuilder(configMap, stateMap, builder);
649 * Map data with different identifiers to builder. Data with different identifiers can be just added
650 * as childs to parent node.
652 * @param configMap map of config data nodes
653 * @param stateMap map of state data nodes
654 * @param builder - builder
656 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
657 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
658 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
659 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
660 y -> builder.addChild(y.getValue()));
661 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
662 y -> builder.addChild(y.getValue()));
666 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
667 * go one level down with {@code prepareData} method.
669 * @param configMap immutable config data
670 * @param stateMap immutable state data
671 * @param builder - builder
673 @SuppressWarnings("unchecked")
674 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
675 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
676 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
677 // it is enough to process only config data because operational contains the same data
678 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
679 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));