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.collect.Iterables;
14 import com.google.common.primitives.Ints;
15 import com.google.common.util.concurrent.FluentFuture;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.List;
21 import java.util.Optional;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24 import javax.ws.rs.core.UriInfo;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
29 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
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.
98 * {@link InstanceIdentifierContext}
102 * set tagged for {@link WriterParameters}
103 * @return {@link WriterParameters}
105 public static @NonNull WriterParameters parseUriParameters(final @NonNull InstanceIdentifierContext<?> identifier,
106 final @Nullable UriInfo uriInfo, final boolean tagged) {
107 return parseParams(identifier, uriInfo, tagged);
111 * Parse parameters from URI request and check their types and values.
115 * {@link InstanceIdentifierContext}
118 * @return {@link WriterParameters}
120 public static @NonNull WriterParameters parseUriParameters(final @NonNull InstanceIdentifierContext<?> identifier,
121 final @Nullable UriInfo uriInfo) {
122 return parseParams(identifier, uriInfo, false);
125 private static WriterParameters parseParams(final InstanceIdentifierContext<?> identifier, final UriInfo uriInfo,
126 final boolean tagged) {
127 final WriterParametersBuilder builder = new WriterParametersBuilder();
128 builder.setTagged(tagged);
130 if (uriInfo == null) {
131 return builder.build();
134 // check only allowed parameters
135 ParametersUtil.checkParametersTypes(
136 RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
137 uriInfo.getQueryParameters().keySet(),
138 RestconfDataServiceConstant.ReadData.CONTENT,
139 RestconfDataServiceConstant.ReadData.DEPTH,
140 RestconfDataServiceConstant.ReadData.FIELDS, RestconfDataServiceConstant.ReadData.WITH_DEFAULTS);
142 // read parameters from URI or set default values
143 final List<String> content = uriInfo.getQueryParameters().getOrDefault(
144 RestconfDataServiceConstant.ReadData.CONTENT,
145 Collections.singletonList(RestconfDataServiceConstant.ReadData.ALL));
146 final List<String> depth = uriInfo.getQueryParameters().getOrDefault(
147 RestconfDataServiceConstant.ReadData.DEPTH,
148 Collections.singletonList(RestconfDataServiceConstant.ReadData.UNBOUNDED));
150 final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
151 RestconfDataServiceConstant.ReadData.FIELDS,
152 Collections.emptyList());
154 // parameter can be in URI at most once
155 ParametersUtil.checkParameterCount(content, RestconfDataServiceConstant.ReadData.CONTENT);
156 ParametersUtil.checkParameterCount(depth, RestconfDataServiceConstant.ReadData.DEPTH);
157 ParametersUtil.checkParameterCount(fields, RestconfDataServiceConstant.ReadData.FIELDS);
159 // check and set content
160 final String contentValue = content.get(0);
161 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.ALL)) {
162 if (!contentValue.equals(RestconfDataServiceConstant.ReadData.CONFIG)
163 && !contentValue.equals(RestconfDataServiceConstant.ReadData.NONCONFIG)) {
164 throw new RestconfDocumentedException(
165 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
166 "Invalid content parameter: " + contentValue, null,
167 "The content parameter value must be either config, nonconfig or all (default)"));
171 builder.setContent(content.get(0));
173 // check and set depth
174 if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
175 final Integer value = Ints.tryParse(depth.get(0));
178 || !(value >= RestconfDataServiceConstant.ReadData.MIN_DEPTH
179 && value <= RestconfDataServiceConstant.ReadData.MAX_DEPTH)) {
180 throw new RestconfDocumentedException(
181 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
182 "Invalid depth parameter: " + depth, null,
183 "The depth parameter must be an integer between 1 and 65535 or \"unbounded\""));
185 builder.setDepth(value);
189 // check and set fields
190 if (!fields.isEmpty()) {
191 builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
194 return builder.build();
198 * Read specific type of data from data store via transaction.
200 * @param valueOfContent
201 * type of data to read (config, state, all)
202 * @param transactionNode
203 * {@link TransactionVarsWrapper} - wrapper for variables
204 * @param schemaContext
206 * @return {@link NormalizedNode}
208 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
209 final @NonNull TransactionVarsWrapper transactionNode, final SchemaContext schemaContext) {
210 return readData(valueOfContent, transactionNode, null, schemaContext);
214 * Read specific type of data from data store via transaction.
216 * @param valueOfContent
217 * type of data to read (config, state, all)
218 * @param transactionNode
219 * {@link TransactionVarsWrapper} - wrapper for variables
221 * vaule of with-defaults parameter
224 * @return {@link NormalizedNode}
226 public static @Nullable NormalizedNode<?, ?> readData(final @NonNull String valueOfContent,
227 final @NonNull TransactionVarsWrapper transactionNode, final String withDefa, final SchemaContext ctx) {
228 switch (valueOfContent) {
229 case RestconfDataServiceConstant.ReadData.CONFIG:
230 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
231 if (withDefa == null) {
232 return readDataViaTransaction(transactionNode);
234 return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
235 transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
237 case RestconfDataServiceConstant.ReadData.NONCONFIG:
238 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
239 return readDataViaTransaction(transactionNode);
241 case RestconfDataServiceConstant.ReadData.ALL:
242 return readAllData(transactionNode, withDefa, ctx);
245 throw new RestconfDocumentedException(
246 new RestconfError(RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.INVALID_VALUE,
247 "Invalid content parameter: " + valueOfContent, null,
248 "The content parameter value must be either config, nonconfig or all (default)"));
253 * Read specific type of data from data store via transaction and if identifier read data from
254 * streams then put streams from actual schema context to datastore.
257 * identifier of data to read
259 * type of data to read (config, state, all)
260 * @param transactionNode
261 * {@link TransactionVarsWrapper} - wrapper for variables
263 * vaule of with-defaults parameter
264 * @param schemaContextRef
268 * @return {@link NormalizedNode}
270 public static NormalizedNode<?, ?> readData(final String identifier, final String content,
271 final TransactionVarsWrapper transactionNode, final String withDefa,
272 final SchemaContextRef schemaContextRef, final UriInfo uriInfo) {
273 final SchemaContext schemaContext = schemaContextRef.get();
274 if (identifier.contains(STREAMS_PATH) && !identifier.contains(STREAM_PATH_PART)) {
275 final DOMDataTreeReadWriteTransaction wTx = transactionNode.getTransactionChain().newReadWriteTransaction();
276 final boolean exist = SubscribeToStreamUtil.checkExist(schemaContext, wTx);
278 for (final NotificationDefinition notificationDefinition : schemaContextRef.get().getNotifications()) {
279 final List<NotificationListenerAdapter> notifiStreamXML =
280 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
281 NotificationOutputType.XML.getName());
282 final List<NotificationListenerAdapter> notifiStreamJSON =
283 CreateStreamUtil.createYangNotifiStream(notificationDefinition, schemaContextRef,
284 NotificationOutputType.JSON.getName());
285 for (final NotificationListenerAdapter listener : Iterables.concat(notifiStreamXML, notifiStreamJSON)) {
286 final URI uri = SubscribeToStreamUtil.prepareUriByStreamName(uriInfo, listener.getStreamName());
287 final NormalizedNode mapToStreams =
288 RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(
289 listener.getSchemaPath().getLastComponent(), schemaContext.getNotifications(),
290 null, listener.getOutputType(), uri,
291 SubscribeToStreamUtil.getMonitoringModule(schemaContext), exist);
292 SubscribeToStreamUtil.writeDataToDS(schemaContext,
293 listener.getSchemaPath().getLastComponent().getLocalName(), wTx, exist,
297 SubscribeToStreamUtil.submitData(wTx);
299 return readData(content, transactionNode, withDefa, schemaContext);
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()))));