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.mdsal.dom.api.DOMTransactionChain;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.context.WriterParameters;
32 import org.opendaylight.restconf.common.context.WriterParameters.WriterParametersBuilder;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError;
35 import org.opendaylight.restconf.nb.rfc8040.references.SchemaContextRef;
36 import org.opendaylight.restconf.nb.rfc8040.rests.transactions.TransactionVarsWrapper;
37 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
38 import org.opendaylight.restconf.nb.rfc8040.utils.mapping.RestconfMappingNodeUtil;
39 import org.opendaylight.restconf.nb.rfc8040.utils.parser.ParserFieldsParameter;
40 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
62 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
67 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
68 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
69 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
70 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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.NotificationDefinition;
75 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 * Util class for read data from data store via transaction.
83 * <li>all (config + state)
87 public final class ReadDataTransactionUtil {
89 private ReadDataTransactionUtil() {
90 throw new UnsupportedOperationException("Util class.");
94 * Parse parameters from URI request and check their types and values.
97 * {@link InstanceIdentifierContext}
100 * @return {@link WriterParameters}
102 public static WriterParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
103 final UriInfo uriInfo) {
104 final WriterParametersBuilder builder = new WriterParametersBuilder();
106 if (uriInfo == null) {
107 return builder.build();
110 // check only allowed parameters
111 ParametersUtil.checkParametersTypes(
112 RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
113 uriInfo.getQueryParameters().keySet(),
114 RestconfDataServiceConstant.ReadData.CONTENT,
115 RestconfDataServiceConstant.ReadData.DEPTH,
116 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
118 // read parameters from URI or set default values
119 final List<String> content = uriInfo.getQueryParameters().getOrDefault(
120 RestconfDataServiceConstant.ReadData.CONTENT,
121 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
122 final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
123 RestconfDataServiceConstant.ReadData.DEPTH,
124 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
125 final List<String> withDefaults = uriInfo.getQueryParameters().getOrDefault(
126 RestconfDataServiceConstant.ReadData.WITH_DEFAULTS,
127 Collections.emptyList());
129 final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
130 RestconfDataServiceConstant.ReadData.FIELDS,
131 Collections.emptyList());
133 // parameter can be in URI at most once
134 ParametersUtil.checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
135 ParametersUtil.checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
136 ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
137 ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
139 // check and set content
140 final String contentValue = content.get(0);
141 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
142 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
143 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
144 throw new RestconfDocumentedException(
145 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
146 "Invalid content parameter: " + contentValue, null,
147 "The content parameter value must be either config, nonconfig or all (default)"));
151 builder.setContent(content.get(0));
153 // check and set depth
154 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
155 final Integer value = Ints.tryParse(depth.get(0));
158 || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH
159 && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) {
160 throw new RestconfDocumentedException(
161 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
162 "Invalid depth parameter: " + depth, null,
163 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
165 builder.setDepth(value);
169 // check and set fields
170 if (!fields.isEmpty()) {
171 builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
174 // check and set withDefaults parameter
175 if (!withDefaults.isEmpty()) {
176 switch (withDefaults.get(0)) {
177 case RestconfDataServiceConstant.ReadData.REPORT_ALL_TAGGED_DEFAULT_VALUE:
178 builder.setTagged(true);
180 case RestconfDataServiceConstant.ReadData.REPORT_ALL_DEFAULT_VALUE:
183 builder.setWithDefault(withDefaults.get(0));
187 return builder.build();
191 * Read specific type of data from data store via transaction.
193 * @param valueOfContent
194 * type of data to read (config, state, all)
195 * @param transactionNode
196 * {@link TransactionVarsWrapper} - wrapper for variables
197 * @param schemaContext
199 * @return {@link NormalizedNode}
201 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
202 final @NonNull TransactionVarsWrapper transactionNode, final SchemaContext schemaContext) {
203 return readData(valueOfContent, transactionNode, null, schemaContext);
207 * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} inside of object
208 * {@link TransactionVarsWrapper} provided as a parameter.
210 * @param valueOfContent
211 * type of data to read (config, state, all)
212 * @param transactionNode
213 * {@link TransactionVarsWrapper} - wrapper for variables
215 * vaule of with-defaults parameter
218 * @return {@link NormalizedNode}
220 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
221 final @NonNull TransactionVarsWrapper transactionNode, final String withDefa, final SchemaContext ctx) {
222 switch (valueOfContent) {
223 case RestconfDataServiceConstant.ReadData.CONFIG:
224 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
225 if (withDefa == null) {
226 return readDataViaTransaction(transactionNode);
228 return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
229 transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
231 case RestconfDataServiceConstant.ReadData.NONCONFIG:
232 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
233 return readDataViaTransaction(transactionNode);
235 case RestconfDataServiceConstant.ReadData.ALL:
236 return readAllData(transactionNode, withDefa, ctx);
239 transactionNode.getTransactionChain().close();
240 throw new RestconfDocumentedException(
241 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
242 "Invalid content parameter: " + valueOfContent, null,
243 "The content parameter value must be either config, nonconfig or all (default)"));
248 * Read specific type of data from data store via transaction and if identifier read data from
249 * streams then put streams from actual schema context to datastore.
252 * identifier of data to read
254 * type of data to read (config, state, all)
255 * @param transactionNode
256 * {@link TransactionVarsWrapper} - wrapper for variables
258 * vaule of with-defaults parameter
259 * @param schemaContextRef
263 * @return {@link NormalizedNode}
265 public static NormalizedNode<?, ?> readData(final String identifier, final String content,
266 final TransactionVarsWrapper transactionNode, final String withDefa,
267 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
268 final SchemaContext schemaContext = schemaContextRef.get();
269 if (identifier != null && identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
270 createAllYangNotificationStreams(transactionNode, schemaContextRef, uriInfo);
272 return readData(content, transactionNode, withDefa, schemaContext);
275 private static void createAllYangNotificationStreams(final TransactionVarsWrapper transactionNode,
276 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
277 final DOMDataTreeReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
278 final boolean exist = SubscribeToStreamUtil.checkExist(schemaContextRef.get(), wTx);
280 for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
281 final NotificationListenerAdapter notifiStreamXML =
282 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
283 NotificationOutputType.XML);
284 final NotificationListenerAdapter notifiStreamJSON =
285 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
286 NotificationOutputType.JSON);
287 writeNotificationStreamToDatastore(schemaContextRef, uriInfo, wTx, exist, notifiStreamXML);
288 writeNotificationStreamToDatastore(schemaContextRef, uriInfo, wTx, exist, notifiStreamJSON);
290 SubscribeToStreamUtil.submitData(wTx);
293 private static void writeNotificationStreamToDatastore(final SchemaContextRef schemaContextRef,
294 final UriInfo uriInfo, final DOMDataTreeReadWriteTransaction readWriteTransaction, final boolean exist,
295 final NotificationListenerAdapter listener) {
296 final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
297 final NormalizedNode mapToStreams = RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
298 listener.getSchemaPath().getLastComponent(), schemaContextRef.get().getNotifications(), null,
299 listener.getOutputType(), uri,
300 SubscribeToStreamUtil.getMonitoringModule(schemaContextRef.get()), exist);
301 SubscribeToStreamUtil.writeDataToDS(schemaContextRef.get(),
302 listener.getSchemaPath().getLastComponent().getLocalName(), readWriteTransaction, exist, mapToStreams);
305 private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
306 final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
316 throw new RestconfDocumentedException("");
319 final DataSchemaContextTree baseSchemaCtxTree = DataSchemaContextTree.from(ctx);
320 final DataSchemaNode baseSchemaNode = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
321 if (result instanceof ContainerNode) {
322 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder =
323 Builders.containerBuilder((ContainerSchemaNode) baseSchemaNode);
324 buildCont(builder, (ContainerNode) result, baseSchemaCtxTree, path, trim);
325 return builder.build();
327 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder =
328 Builders.mapEntryBuilder((ListSchemaNode) baseSchemaNode);
329 buildMapEntryBuilder(builder, (MapEntryNode) result, baseSchemaCtxTree, path, trim,
330 ((ListSchemaNode) baseSchemaNode).getKeyDefinition());
331 return builder.build();
335 private static void buildMapEntryBuilder(
336 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
337 final MapEntryNode result, final DataSchemaContextTree baseSchemaCtxTree,
338 final YangInstanceIdentifier actualPath, final boolean trim, final List<QName> keys) {
339 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
340 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
341 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
342 if (child instanceof ContainerNode) {
343 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> childBuilder =
344 Builders.containerBuilder((ContainerSchemaNode) childSchema);
345 buildCont(childBuilder, (ContainerNode) child, baseSchemaCtxTree, path, trim);
346 builder.withChild(childBuilder.build());
347 } else if (child instanceof MapNode) {
348 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
349 Builders.mapBuilder((ListSchemaNode) childSchema);
350 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
351 ((ListSchemaNode) childSchema).getKeyDefinition());
352 builder.withChild(childBuilder.build());
353 } else if (child instanceof LeafNode) {
354 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
355 final Object nodeVal = child.getValue();
356 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
357 Builders.leafBuilder((LeafSchemaNode) childSchema);
358 if (keys.contains(child.getNodeType())) {
359 leafBuilder.withValue(((LeafNode) child).getValue());
360 builder.withChild(leafBuilder.build());
363 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
364 leafBuilder.withValue(((LeafNode) child).getValue());
365 builder.withChild(leafBuilder.build());
368 if (defaultVal != null && defaultVal.equals(nodeVal)) {
369 leafBuilder.withValue(((LeafNode) child).getValue());
370 builder.withChild(leafBuilder.build());
378 private static void buildList(final CollectionNodeBuilder<MapEntryNode, MapNode> builder, final MapNode result,
379 final DataSchemaContextTree baseSchemaCtxTree, final YangInstanceIdentifier path, final boolean trim,
380 final List<QName> keys) {
381 for (final MapEntryNode mapEntryNode : result.getValue()) {
382 final YangInstanceIdentifier actualNode = path.node(mapEntryNode.getIdentifier());
383 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(actualNode).getDataSchemaNode();
384 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder =
385 Builders.mapEntryBuilder((ListSchemaNode) childSchema);
386 buildMapEntryBuilder(mapEntryBuilder, mapEntryNode, baseSchemaCtxTree, actualNode, trim, keys);
387 builder.withChild(mapEntryBuilder.build());
391 private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
392 final ContainerNode result, final DataSchemaContextTree baseSchemaCtxTree,
393 final YangInstanceIdentifier actualPath, final boolean trim) {
394 for (final DataContainerChild<? extends PathArgument, ?> child : result.getValue()) {
395 final YangInstanceIdentifier path = actualPath.node(child.getIdentifier());
396 final DataSchemaNode childSchema = baseSchemaCtxTree.getChild(path).getDataSchemaNode();
397 if (child instanceof ContainerNode) {
398 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builderChild =
399 Builders.containerBuilder((ContainerSchemaNode) childSchema);
400 buildCont(builderChild, result, baseSchemaCtxTree, actualPath, trim);
401 builder.withChild(builderChild.build());
402 } else if (child instanceof MapNode) {
403 final CollectionNodeBuilder<MapEntryNode, MapNode> childBuilder =
404 Builders.mapBuilder((ListSchemaNode) childSchema);
405 buildList(childBuilder, (MapNode) child, baseSchemaCtxTree, path, trim,
406 ((ListSchemaNode) childSchema).getKeyDefinition());
407 builder.withChild(childBuilder.build());
408 } else if (child instanceof LeafNode) {
409 final Object defaultVal = ((LeafSchemaNode) childSchema).getType().getDefaultValue().orElse(null);
410 final Object nodeVal = child.getValue();
411 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
412 Builders.leafBuilder((LeafSchemaNode) childSchema);
414 if (defaultVal == null || !defaultVal.equals(nodeVal)) {
415 leafBuilder.withValue(((LeafNode) child).getValue());
416 builder.withChild(leafBuilder.build());
419 if (defaultVal != null && defaultVal.equals(nodeVal)) {
420 leafBuilder.withValue(((LeafNode) child).getValue());
421 builder.withChild(leafBuilder.build());
429 * If is set specific {@link LogicalDatastoreType} in
430 * {@link TransactionVarsWrapper}, then read this type of data from DS. If
431 * don't, we have to read all data from DS (state + config).
432 * This method will close {@link org.opendaylight.mdsal.dom.api.DOMTransactionChain} inside of
433 * {@link TransactionVarsWrapper}.
435 * @param transactionNode
436 * {@link TransactionVarsWrapper} - wrapper for variables
437 * @return {@link NormalizedNode}
439 private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
440 final @NonNull TransactionVarsWrapper transactionNode) {
441 return readDataViaTransaction(transactionNode, true);
446 * If is set specific {@link LogicalDatastoreType} in
447 * {@link TransactionVarsWrapper}, then read this type of data from DS. If
448 * don't, we have to read all data from DS (state + config)
450 * @param transactionNode
451 * {@link TransactionVarsWrapper} - wrapper for variables
452 * @param closeTransactionChain
453 * If is set to true, after transaction it will close transactionChain in {@link TransactionVarsWrapper}
454 * @return {@link NormalizedNode}
456 private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
457 final @NonNull TransactionVarsWrapper transactionNode, final boolean closeTransactionChain) {
458 final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
459 try (DOMDataTreeReadTransaction tx = transactionNode.getTransactionChain().newReadOnlyTransaction()) {
460 final FluentFuture<Optional<NormalizedNode<?, ?>>> listenableFuture = tx.read(
461 transactionNode.getLogicalDatastoreType(),
462 transactionNode.getInstanceIdentifier().getInstanceIdentifier());
463 if (closeTransactionChain) {
464 //Method close transactionChain inside of TransactionVarsWrapper, if is provide as a parameter.
465 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
466 dataFactory, transactionNode.getTransactionChain());
468 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
472 return dataFactory.build();
476 * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
477 * {@link TransactionVarsWrapper} provided as a parameter.
479 * @param transactionNode
480 * {@link TransactionVarsWrapper} - wrapper for variables
482 * with-defaults parameter
485 * @return {@link NormalizedNode}
487 private static @Nullable NormalizedNode<?, ?> readAllData(final @NonNull TransactionVarsWrapper transactionNode,
488 final String withDefa, final SchemaContext ctx) {
489 // PREPARE STATE DATA NODE
490 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
491 final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(transactionNode, false);
493 // PREPARE CONFIG DATA NODE
494 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
495 final NormalizedNode<?, ?> configDataNode;
496 //Here will be closed transactionChain
497 if (withDefa == null) {
498 configDataNode = readDataViaTransaction(transactionNode);
500 configDataNode = prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
501 transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
505 if (stateDataNode == null && configDataNode == null) {
509 // return config data
510 if (stateDataNode == null) {
511 return configDataNode;
515 if (configDataNode == null) {
516 return stateDataNode;
519 // merge data from config and state
520 return mergeStateAndConfigData(stateDataNode, configDataNode);
524 * Merge state and config data into a single NormalizedNode.
526 * @param stateDataNode
527 * data node of state data
528 * @param configDataNode
529 * data node of config data
530 * @return {@link NormalizedNode}
532 private static @NonNull NormalizedNode<?, ?> mergeStateAndConfigData(
533 final @NonNull NormalizedNode<?, ?> stateDataNode, final @NonNull NormalizedNode<?, ?> configDataNode) {
534 validateNodeMerge(stateDataNode, configDataNode);
535 if (configDataNode instanceof RpcDefinition) {
536 return prepareRpcData(configDataNode, stateDataNode);
538 return prepareData(configDataNode, stateDataNode);
543 * Validates whether the two NormalizedNodes can be merged.
545 * @param stateDataNode
546 * data node of state data
547 * @param configDataNode
548 * data node of config data
550 private static void validateNodeMerge(final @NonNull NormalizedNode<?, ?> stateDataNode,
551 final @NonNull NormalizedNode<?, ?> configDataNode) {
552 final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
553 final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
554 if (!moduleOfStateData.equals(moduleOfConfigData)) {
555 throw new RestconfDocumentedException("Unable to merge data from different modules.");
560 * Prepare and map data for rpc.
562 * @param configDataNode
563 * data node of config data
564 * @param stateDataNode
565 * data node of state data
566 * @return {@link NormalizedNode}
568 private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
569 final @NonNull NormalizedNode<?, ?> stateDataNode) {
570 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
572 mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
575 mapRpcDataNode(configDataNode, mapEntryBuilder);
577 mapRpcDataNode(stateDataNode, mapEntryBuilder);
579 return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
583 * Map node to map entry builder.
587 * @param mapEntryBuilder
588 * builder for mapping data
590 private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
591 final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
592 ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
596 * Prepare and map all data from DS.
598 * @param configDataNode
599 * data node of config data
600 * @param stateDataNode
601 * data node of state data
602 * @return {@link NormalizedNode}
604 @SuppressWarnings("unchecked")
605 private static @NonNull NormalizedNode<?, ?> prepareData(final @NonNull NormalizedNode<?, ?> configDataNode,
606 final @NonNull NormalizedNode<?, ?> stateDataNode) {
607 if (configDataNode instanceof OrderedMapNode) {
608 final CollectionNodeBuilder<MapEntryNode, OrderedMapNode> builder = Builders
609 .orderedMapBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
612 ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
614 return builder.build();
615 } else if (configDataNode instanceof MapNode) {
616 final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
617 .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
620 ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
622 return builder.build();
623 } else if (configDataNode instanceof MapEntryNode) {
624 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
625 .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
628 ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
630 return builder.build();
631 } else if (configDataNode instanceof ContainerNode) {
632 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
633 .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
636 ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
638 return builder.build();
639 } else if (configDataNode instanceof AugmentationNode) {
640 final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
641 .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
643 mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
644 ((AugmentationNode) stateDataNode).getValue(), builder);
646 return builder.build();
647 } else if (configDataNode instanceof ChoiceNode) {
648 final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
649 .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
652 ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
654 return builder.build();
655 } else if (configDataNode instanceof LeafNode) {
656 return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
657 } else if (configDataNode instanceof OrderedLeafSetNode) {
658 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
659 .orderedLeafSetBuilder().withNodeIdentifier(((OrderedLeafSetNode<?>) configDataNode).getIdentifier());
661 mapValueToBuilder(((OrderedLeafSetNode<Object>) configDataNode).getValue(),
662 ((OrderedLeafSetNode<Object>) stateDataNode).getValue(), builder);
663 return builder.build();
664 } else if (configDataNode instanceof LeafSetNode) {
665 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder = Builders
666 .leafSetBuilder().withNodeIdentifier(((LeafSetNode<?>) configDataNode).getIdentifier());
668 mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
669 ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
670 return builder.build();
671 } else if (configDataNode instanceof LeafSetEntryNode) {
672 final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>>
673 builder = Builders.leafSetEntryBuilder().withNodeIdentifier(((LeafSetEntryNode<?>) configDataNode)
674 .getIdentifier()).withValue(configDataNode.getValue());
675 return builder.build();
676 } else if (configDataNode instanceof UnkeyedListNode) {
677 final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
678 .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
680 mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
681 ((UnkeyedListNode) stateDataNode).getValue(), builder);
682 return builder.build();
683 } else if (configDataNode instanceof UnkeyedListEntryNode) {
684 final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
685 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
687 mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
688 ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
689 return builder.build();
691 throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
696 * Map value from container node to builder.
699 * collection of config data nodes
701 * collection of state data nodes
705 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
706 final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
707 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
708 final Map<PathArgument, T> configMap = configData.stream().collect(
709 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
710 final Map<PathArgument, T> stateMap = stateData.stream().collect(
711 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
713 // merge config and state data of children with different identifiers
714 mapDataToBuilder(configMap, stateMap, builder);
716 // merge config and state data of children with the same identifiers
717 mergeDataToBuilder(configMap, stateMap, builder);
721 * Map data with different identifiers to builder. Data with different identifiers can be just added
722 * as childs to parent node.
725 * map of config data nodes
727 * map of state data nodes
731 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
732 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
733 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
734 configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
735 y -> builder.addChild(y.getValue()));
736 stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
737 y -> builder.addChild(y.getValue()));
741 * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
742 * go one level down with {@code prepareData} method.
745 * immutable config data
747 * immutable state data
751 @SuppressWarnings("unchecked")
752 private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
753 final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
754 final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
755 // it is enough to process only config data because operational contains the same data
756 configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
757 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));