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.rests.utils.RestconfStreamsConstants.STREAMS_PATH;
11 import static org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants.STREAM_PATH_PART;
13 import com.google.common.primitives.Ints;
14 import com.google.common.util.concurrent.FluentFuture;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
20 import java.util.Optional;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
23 import javax.ws.rs.core.UriInfo;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.context.WriterParameters;
31 import org.opendaylight.restconf.common.context.WriterParameters.WriterParametersBuilder;
32 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
33 import org.opendaylight.restconf.common.errors.RestconfError;
34 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
35 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
36 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
37 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
38 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter;
39 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.QNameModule;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
61 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
62 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
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.LeafSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
74 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 * Util class for read data from data store via transaction.
82 * <li>all (config + state)
86 public final class ReadDataTransactionUtil {
88 private ReadDataTransactionUtil() {
89 throw new UnsupportedOperationException("Util class.");
93 * Parse parameters from URI request and check their types and values.
96 * {@link InstanceIdentifierContext}
99 * @return {@link WriterParameters}
101 public static WriterParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
102 final UriInfo uriInfo) {
103 final WriterParametersBuilder builder = new WriterParametersBuilder();
105 if (uriInfo == null) {
106 return builder.build();
109 // check only allowed parameters
110 ParametersUtil.checkParametersTypes(
111 RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
112 uriInfo.getQueryParameters().keySet(),
113 RestconfDataServiceConstant.ReadData.CONTENT,
114 RestconfDataServiceConstant.ReadData.DEPTH,
115 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
117 // read parameters from URI or set default values
118 final List<String> content = uriInfo.getQueryParameters().getOrDefault(
119 RestconfDataServiceConstant.ReadData.CONTENT,
120 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
121 final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
122 RestconfDataServiceConstant.ReadData.DEPTH,
123 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
124 final List<String> withDefaults = uriInfo.getQueryParameters().getOrDefault(
125 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS,
126 Collections.emptyList());
128 final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
129 RestconfDataServiceConstant.ReadData.FIELDS,
130 Collections.emptyList());
132 // parameter can be in URI at most once
133 ParametersUtil.checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
134 ParametersUtil.checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
135 ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
136 ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
138 // check and set content
139 final String contentValue = content.get(0);
140 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
141 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
142 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
143 throw new RestconfDocumentedException(
144 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
145 "Invalid content parameter: " + contentValue, null,
146 "The content parameter value must be either config, nonconfig or all (default)"));
150 builder.setContent(content.get(0));
152 // check and set depth
153 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
154 final Integer value = Ints.tryParse(depth.get(0));
157 || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH
158 && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) {
159 throw new RestconfDocumentedException(
160 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
161 "Invalid depth parameter: " + depth, null,
162 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
164 builder.setDepth(value);
168 // check and set fields
169 if (!fields.isEmpty()) {
170 builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
173 // check and set withDefaults parameter
174 if (!withDefaults.isEmpty()) {
175 switch (withDefaults.get(0)) {
176 case RestconfDataServiceConstant.ReadData.REPORT_ALL_TAGGED_DEFAULT_VALUE:
177 builder.setTagged(true);
179 case RestconfDataServiceConstant.ReadData.REPORT_ALL_DEFAULT_VALUE:
182 builder.setWithDefault(withDefaults.get(0));
186 return builder.build();
190 * Read specific type of data from data store via transaction.
192 * @param valueOfContent
193 * type of data to read (config, state, all)
194 * @param transactionNode
195 * {@link TransactionVarsWrapper} - wrapper for variables
196 * @param schemaContext
198 * @return {@link NormalizedNode}
200 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
201 final @NonNull TransactionVarsWrapper transactionNode, final SchemaContext schemaContext) {
202 return readData(valueOfContent, transactionNode, null, schemaContext);
206 * Read specific type of data from data store via transaction.
208 * @param valueOfContent
209 * type of data to read (config, state, all)
210 * @param transactionNode
211 * {@link TransactionVarsWrapper} - wrapper for variables
213 * vaule of with-defaults parameter
216 * @return {@link NormalizedNode}
218 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
219 final @NonNull TransactionVarsWrapper transactionNode, final String withDefa, final SchemaContext ctx) {
220 switch (valueOfContent) {
221 case RestconfDataServiceConstant.ReadData.CONFIG:
222 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
223 if (withDefa == null) {
224 return readDataViaTransaction(transactionNode);
226 return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
227 transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
229 case RestconfDataServiceConstant.ReadData.NONCONFIG:
230 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
231 return readDataViaTransaction(transactionNode);
233 case RestconfDataServiceConstant.ReadData.ALL:
234 return readAllData(transactionNode, withDefa, ctx);
237 throw new RestconfDocumentedException(
238 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
239 "Invalid content parameter: " + valueOfContent, null,
240 "The content parameter value must be either config, nonconfig or all (default)"));
245 * Read specific type of data from data store via transaction and if identifier read data from
246 * streams then put streams from actual schema context to datastore.
249 * identifier of data to read
251 * type of data to read (config, state, all)
252 * @param transactionNode
253 * {@link TransactionVarsWrapper} - wrapper for variables
255 * vaule of with-defaults parameter
256 * @param schemaContextRef
260 * @return {@link NormalizedNode}
262 public static NormalizedNode<?, ?> readData(final String identifier, final String content,
263 final TransactionVarsWrapper transactionNode, final String withDefa,
264 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
265 final SchemaContext schemaContext = schemaContextRef.get();
266 if (identifier != null && identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
267 createAllYangNotificationStreams(transactionNode, schemaContextRef, uriInfo);
269 return readData(content, transactionNode, withDefa, schemaContext);
272 private static void createAllYangNotificationStreams(final TransactionVarsWrapper transactionNode,
273 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
274 final DOMDataTreeReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
275 final boolean exist = SubscribeToStreamUtil.checkExist(schemaContextRef.get(), wTx);
277 for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
278 final NotificationListenerAdapter notifiStreamXML =
279 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
280 NotificationOutputType.XML);
281 final NotificationListenerAdapter notifiStreamJSON =
282 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
283 NotificationOutputType.JSON);
284 writeNotificationStreamToDatastore(schemaContextRef, uriInfo, wTx, exist, notifiStreamXML);
285 writeNotificationStreamToDatastore(schemaContextRef, uriInfo, wTx, exist, notifiStreamJSON);
287 SubscribeToStreamUtil.submitData(wTx);
290 private static void writeNotificationStreamToDatastore(final SchemaContextRef schemaContextRef,
291 final UriInfo uriInfo, final DOMDataTreeReadWriteTransaction readWriteTransaction, final boolean exist,
292 final NotificationListenerAdapter listener) {
293 final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
294 final NormalizedNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
295 listener.getSchemaPath().getLastComponent(), schemaContextRef.get().getNotifications(), null,
296 listener.getOutputType(), uri,
297 SubscribeToStreamUtil.getMonitoringModule(schemaContextRef.get()), exist);
298 SubscribeToStreamUtil.writeDataToDS(schemaContextRef.get(),
299 listener.getSchemaPath().getLastComponent().getLocalName(), readWriteTransaction, exist, mapToStreams);
302 private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
303 final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
313 throw new RestconfDocumentedException("");
316 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
317 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
318 if (result instanceof ContainerNode) {
319 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
320 Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
321 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
322 return builder.build();
324 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
325 Builders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
326 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
327 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
328 return builder.build();
332 private static void buildMapEntryBuilder(
333 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
334 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
335 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
336 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
337 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
338 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
339 if (child instanceof ContainerNode) {
340 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
341 Builders.containerBuilder((ContainerSchemaNode) childSchema);
342 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
343 builder.withChild(childBuilder.build());
344 } else if (child instanceof MapNode) {
345 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
346 Builders.mapBuilder((ListSchemaNode) childSchema);
347 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
348 ((ListSchemaNode) childSchema).getKeyDefinition());
349 builder.withChild(childBuilder.build());
350 } else if (child instanceof LeafNode) {
351 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
352 final Object nodeVal = child.getValue();
353 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
354 Builders.leafBuilder((LeafSchemaNode) childSchema);
355 if (keys.contains(child.getNodeType())) {
356 leafBuilder.withValue(((LeafNode) child).getValue());
357 builder.withChild(leafBuilder.build());
360 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
361 leafBuilder.withValue(((LeafNode) child).getValue());
362 builder.withChild(leafBuilder.build());
365 if (defaultVal != null && defaultVal.equals(nodeVal)) {
366 leafBuilder.withValue(((LeafNode) child).getValue());
367 builder.withChild(leafBuilder.build());
375 private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
376 final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
377 final List<QName> keys) {
378 for (final MapEntryNode mapEntryNode : result.getValue()) {
379 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
380 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(actualNode).getDataSchemaNode();
381 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
382 Builders.mapEntryBuilder((ListSchemaNode) childSchema);
383 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
384 builder.withChild(mapEntryBuilder.build());
388 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
389 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
390 final YangInstanceIdentifier actualPath, final boolean trim) {
391 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
392 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
393 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
394 if (child instanceof ContainerNode) {
395 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
396 Builders.containerBuilder((ContainerSchemaNode) childSchema);
397 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
398 builder.withChild(builderChild.build());
399 } else if (child instanceof MapNode) {
400 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
401 Builders.mapBuilder((ListSchemaNode) childSchema);
402 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
403 ((ListSchemaNode) childSchema).getKeyDefinition());
404 builder.withChild(childBuilder.build());
405 } else if (child instanceof LeafNode) {
406 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
407 final Object nodeVal = child.getValue();
408 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
409 Builders.leafBuilder((LeafSchemaNode) childSchema);
411 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
412 leafBuilder.withValue(((LeafNode) child).getValue());
413 builder.withChild(leafBuilder.build());
416 if (defaultVal != null && defaultVal.equals(nodeVal)) {
417 leafBuilder.withValue(((LeafNode) child).getValue());
418 builder.withChild(leafBuilder.build());
426 * If is set specific {@link LogicalDatastoreType} in
427 * {@link TransactionVarsWrapper}, then read this type of data from DS. If
428 * don't, we have to read all data from DS (state + config)
430 * @param transactionNode
431 * {@link TransactionVarsWrapper} - wrapper for variables
432 * @return {@link NormalizedNode}
434 private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
435 final @NonNull TransactionVarsWrapper transactionNode) {
436 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
437 try (DOMDataTreeReadTransaction tx = transactionNode.getTransactionChain().newReadOnlyTransaction()) {
438 final FluentFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = tx.read(
439 transactionNode.getLogicalDatastoreType(),
440 transactionNode.getInstanceIdentifier().getInstanceIdentifier());
441 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
444 return dataFactory.build();
448 * Read config and state data, then map them.
450 * @param transactionNode
451 * {@link TransactionVarsWrapper} - wrapper for variables
453 * with-defaults parameter
456 * @return {@link NormalizedNode}
458 private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull TransactionVarsWrapper transactionNode,
459 final String withDefa, final SchemaContext ctx) {
460 // PREPARE STATE DATA NODE
461 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
462 final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(transactionNode);
464 // PREPARE CONFIG DATA NODE
465 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
466 final NormalizedNode<?, ?> configDataNode;
467 if (withDefa == null) {
468 configDataNode = readDataViaTransaction(transactionNode);
470 configDataNode = prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
471 transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
475 if (stateDataNode == null && configDataNode == null) {
479 // return config data
480 if (stateDataNode == null) {
481 return configDataNode;
485 if (configDataNode == null) {
486 return stateDataNode;
489 // merge data from config and state
490 return mergeStateAndConfigData(stateDataNode, configDataNode);
494 * Merge state and config data into a single NormalizedNode.
496 * @param stateDataNode
497 * data node of state data
498 * @param configDataNode
499 * data node of config data
500 * @return {@link NormalizedNode}
502 private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
503 final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
504 validateNodeMerge(stateDataNode, configDataNode);
505 if (configDataNode instanceof RpcDefinition) {
506 return prepareRpcData(configDataNode, stateDataNode);
508 return prepareData(configDataNode, stateDataNode);
513 * Validates whether the two NormalizedNodes can be merged.
515 * @param stateDataNode
516 * data node of state data
517 * @param configDataNode
518 * data node of config data
520 private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
521 final @NonNull NormalizedNode<?, ?> configDataNode) {
522 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
523 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
524 if (!moduleOfStateData.equals(moduleOfConfigData)) {
525 throw new RestconfDocumentedException("Unable to merge data from different modules.");
530 * Prepare and map data for rpc.
532 * @param configDataNode
533 * data node of config data
534 * @param stateDataNode
535 * data node of state data
536 * @return {@link NormalizedNode}
538 private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
539 final @NonNull NormalizedNode<?, ?> stateDataNode) {
540 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
542 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
545 mapRpcDataNode(configDataNode, mapEntryBuilder);
547 mapRpcDataNode(stateDataNode, mapEntryBuilder);
549 return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
553 * Map node to map entry builder.
557 * @param mapEntryBuilder
558 * builder for mapping data
560 private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
561 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
562 ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
566 * Prepare and map all data from DS.
568 * @param configDataNode
569 * data node of config data
570 * @param stateDataNode
571 * data node of state data
572 * @return {@link NormalizedNode}
574 @SuppressWarnings("unchecked")
575 private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
576 final @NonNull NormalizedNode<?, ?> stateDataNode) {
577 if (configDataNode instanceof OrderedMapNode) {
578 final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
579 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
582 ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
584 return builder.build();
585 } else if (configDataNode instanceof MapNode) {
586 final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
587 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
590 ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
592 return builder.build();
593 } else if (configDataNode instanceof MapEntryNode) {
594 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
595 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
598 ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
600 return builder.build();
601 } else if (configDataNode instanceof ContainerNode) {
602 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
603 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
606 ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
608 return builder.build();
609 } else if (configDataNode instanceof AugmentationNode) {
610 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
611 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
613 mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
614 ((AugmentationNode) stateDataNode).getValue(), builder);
616 return builder.build();
617 } else if (configDataNode instanceof ChoiceNode) {
618 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
619 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
622 ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
624 return builder.build();
625 } else if (configDataNode instanceof LeafNode) {
626 return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
627 } else if (configDataNode instanceof OrderedLeafSetNode) {
628 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
629 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
631 mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
632 ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
633 return builder.build();
634 } else if (configDataNode instanceof LeafSetNode) {
635 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
636 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
638 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
639 ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
640 return builder.build();
641 } else if (configDataNode instanceof UnkeyedListNode) {
642 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
643 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
645 mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
646 ((UnkeyedListNode) stateDataNode).getValue(), builder);
647 return builder.build();
648 } else if (configDataNode instanceof UnkeyedListEntryNode) {
649 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
650 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
652 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
653 ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
654 return builder.build();
656 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
661 * Map value from container node to builder.
664 * collection of config data nodes
666 * collection of state data nodes
670 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
671 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
672 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
673 final Map<PathArgument, T> configMap = configData.stream().collect(
674 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
675 final Map<PathArgument, T> stateMap = stateData.stream().collect(
676 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
678 // merge config and state data of children with different identifiers
679 mapDataToBuilder(configMap, stateMap, builder);
681 // merge config and state data of children with the same identifiers
682 mergeDataToBuilder(configMap, stateMap, builder);
686 * Map data with different identifiers to builder. Data with different identifiers can be just added
687 * as childs to parent node.
690 * map of config data nodes
692 * map of state data nodes
696 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
697 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
698 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
699 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
700 y -> builder.addChild(y.getValue()));
701 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
702 y -> builder.addChild(y.getValue()));
706 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
707 * go one level down with {@code prepareData} method.
710 * immutable config data
712 * immutable state data
716 @SuppressWarnings("unchecked")
717 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
718 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
719 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
720 // it is enough to process only config data because operational contains the same data
721 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
722 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));