Reorganize transactionChainHandler usage.
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / utils / ReadDataTransactionUtil.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.rests.utils;
9
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;
12
13 import com.google.common.primitives.Ints;
14 import com.google.common.util.concurrent.FluentFuture;
15 import java.net.URI;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.Map;
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;
77
78 /**
79  * Util class for read data from data store via transaction.
80  * <ul>
81  * <li>config
82  * <li>state
83  * <li>all (config + state)
84  * </ul>
85  *
86  */
87 public final class ReadDataTransactionUtil {
88
89     private ReadDataTransactionUtil() {
90         throw new UnsupportedOperationException("Util class.");
91     }
92
93     /**
94      * Parse parameters from URI request and check their types and values.
95      *
96      * @param identifier
97      *             {@link InstanceIdentifierContext}
98      * @param uriInfo
99      *             URI info
100      * @return {@link WriterParameters}
101      */
102     public static WriterParameters parseUriParameters(final InstanceIdentifierContext<?> identifier,
103                                                       final UriInfo uriInfo) {
104         final WriterParametersBuilder builder = new WriterParametersBuilder();
105
106         if (uriInfo == null) {
107             return builder.build();
108         }
109
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);
117
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());
128         // fields
129         final List<String> fields = uriInfo.getQueryParameters().getOrDefault(
130                 RestconfDataServiceConstant.ReadData.FIELDS,
131                 Collections.emptyList());
132
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);
138
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)"));
148             }
149         }
150
151         builder.setContent(content.get(0));
152
153         // check and set depth
154         if (!depth.get(0).equals(RestconfDataServiceConstant.ReadData.UNBOUNDED)) {
155             final Integer value = Ints.tryParse(depth.get(0));
156
157             if (value == null
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\""));
164             } else {
165                 builder.setDepth(value);
166             }
167         }
168
169         // check and set fields
170         if (!fields.isEmpty()) {
171             builder.setFields(ParserFieldsParameter.parseFieldsParameter(identifier, fields.get(0)));
172         }
173
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);
179                     break;
180                 case RestconfDataServiceConstant.ReadData.REPORT_ALL_DEFAULT_VALUE:
181                     break;
182                 default:
183                     builder.setWithDefault(withDefaults.get(0));
184             }
185         }
186
187         return builder.build();
188     }
189
190     /**
191      * Read specific type of data from data store via transaction.
192      *
193      * @param valueOfContent
194      *            type of data to read (config, state, all)
195      * @param transactionNode
196      *            {@link TransactionVarsWrapper} - wrapper for variables
197      * @param schemaContext
198      *            schema context
199      * @return {@link NormalizedNode}
200      */
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);
204     }
205
206     /**
207      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} inside of object
208      * {@link TransactionVarsWrapper} provided as a parameter.
209      *
210      * @param valueOfContent
211      *            type of data to read (config, state, all)
212      * @param transactionNode
213      *            {@link TransactionVarsWrapper} - wrapper for variables
214      * @param withDefa
215      *            vaule of with-defaults parameter
216      * @param ctx
217      *            schema context
218      * @return {@link NormalizedNode}
219      */
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);
227                 } else {
228                     return prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
229                             transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
230                 }
231             case RestconfDataServiceConstant.ReadData.NONCONFIG:
232                 transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
233                 return readDataViaTransaction(transactionNode);
234
235             case RestconfDataServiceConstant.ReadData.ALL:
236                 return readAllData(transactionNode, withDefa, ctx);
237
238             default:
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)"));
244         }
245     }
246
247     /**
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.
250      *
251      * @param identifier
252      *             identifier of data to read
253      * @param content
254      *             type of data to read (config, state, all)
255      * @param transactionNode
256      *             {@link TransactionVarsWrapper} - wrapper for variables
257      * @param withDefa
258      *             vaule of with-defaults parameter
259      * @param schemaContextRef
260      *             schema context
261      * @param uriInfo
262      *             uri info
263      * @return {@link NormalizedNode}
264      */
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);
271         }
272         return readData(content, transactionNode, withDefa, schemaContext);
273     }
274
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);
279
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);
289         }
290         SubscribeToStreamUtil.submitData(wTx);
291     }
292
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);
303     }
304
305     private static NormalizedNode<?, ?> prepareDataByParamWithDef(final NormalizedNode<?, ?> result,
306             final YangInstanceIdentifier path, final String withDefa, final SchemaContext ctx) {
307         boolean trim;
308         switch (withDefa) {
309             case "trim":
310                 trim = true;
311                 break;
312             case "explicit":
313                 trim = false;
314                 break;
315             default:
316                 throw new RestconfDocumentedException("");
317         }
318
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();
326         } else {
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();
332         }
333     }
334
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());
361                 } else {
362                     if (trim) {
363                         if (defaultVal == null || !defaultVal.equals(nodeVal)) {
364                             leafBuilder.withValue(((LeafNode) child).getValue());
365                             builder.withChild(leafBuilder.build());
366                         }
367                     } else {
368                         if (defaultVal != null && defaultVal.equals(nodeVal)) {
369                             leafBuilder.withValue(((LeafNode) child).getValue());
370                             builder.withChild(leafBuilder.build());
371                         }
372                     }
373                 }
374             }
375         }
376     }
377
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());
388         }
389     }
390
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);
413                 if (trim) {
414                     if (defaultVal == null || !defaultVal.equals(nodeVal)) {
415                         leafBuilder.withValue(((LeafNode) child).getValue());
416                         builder.withChild(leafBuilder.build());
417                     }
418                 } else {
419                     if (defaultVal != null && defaultVal.equals(nodeVal)) {
420                         leafBuilder.withValue(((LeafNode) child).getValue());
421                         builder.withChild(leafBuilder.build());
422                     }
423                 }
424             }
425         }
426     }
427
428     /**
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}.
434      *
435      * @param transactionNode
436      *             {@link TransactionVarsWrapper} - wrapper for variables
437      * @return {@link NormalizedNode}
438      */
439     private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
440             final @NonNull TransactionVarsWrapper transactionNode) {
441         return readDataViaTransaction(transactionNode, true);
442     }
443
444
445     /**
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)
449      *
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}
455      */
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());
467             } else {
468                 FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
469                         dataFactory);
470             }
471         }
472         return dataFactory.build();
473     }
474
475     /**
476      * Read config and state data, then map them. Close {@link DOMTransactionChain} inside of object
477      * {@link TransactionVarsWrapper} provided as a parameter.
478      *
479      * @param transactionNode
480      *            {@link TransactionVarsWrapper} - wrapper for variables
481      * @param withDefa
482      *            with-defaults parameter
483      * @param ctx
484      *            schema context
485      * @return {@link NormalizedNode}
486      */
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);
492
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);
499         } else {
500             configDataNode = prepareDataByParamWithDef(readDataViaTransaction(transactionNode),
501                     transactionNode.getInstanceIdentifier().getInstanceIdentifier(), withDefa, ctx);
502         }
503
504         // if no data exists
505         if (stateDataNode == null && configDataNode == null) {
506             return null;
507         }
508
509         // return config data
510         if (stateDataNode == null) {
511             return configDataNode;
512         }
513
514         // return state data
515         if (configDataNode == null) {
516             return stateDataNode;
517         }
518
519         // merge data from config and state
520         return mergeStateAndConfigData(stateDataNode, configDataNode);
521     }
522
523     /**
524      * Merge state and config data into a single NormalizedNode.
525      *
526      * @param stateDataNode
527      *             data node of state data
528      * @param configDataNode
529      *             data node of config data
530      * @return {@link NormalizedNode}
531      */
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);
537         } else {
538             return prepareData(configDataNode, stateDataNode);
539         }
540     }
541
542     /**
543      * Validates whether the two NormalizedNodes can be merged.
544      *
545      * @param stateDataNode
546      *             data node of state data
547      * @param configDataNode
548      *             data node of config data
549      */
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.");
556         }
557     }
558
559     /**
560      * Prepare and map data for rpc.
561      *
562      * @param configDataNode
563      *             data node of config data
564      * @param stateDataNode
565      *             data node of state data
566      * @return {@link NormalizedNode}
567      */
568     private static @NonNull NormalizedNode<?, ?> prepareRpcData(final @NonNull NormalizedNode<?, ?> configDataNode,
569                                                                 final @NonNull NormalizedNode<?, ?> stateDataNode) {
570         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
571                 .mapEntryBuilder();
572         mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
573
574         // MAP CONFIG DATA
575         mapRpcDataNode(configDataNode, mapEntryBuilder);
576         // MAP STATE DATA
577         mapRpcDataNode(stateDataNode, mapEntryBuilder);
578
579         return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
580     }
581
582     /**
583      * Map node to map entry builder.
584      *
585      * @param dataNode
586      *             data node
587      * @param mapEntryBuilder
588      *             builder for mapping data
589      */
590     private static void mapRpcDataNode(final @NonNull NormalizedNode<?, ?> dataNode,
591             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
592         ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
593     }
594
595     /**
596      * Prepare and map all data from DS.
597      *
598      * @param configDataNode
599      *             data node of config data
600      * @param stateDataNode
601      *             data node of state data
602      * @return {@link NormalizedNode}
603      */
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());
610
611             mapValueToBuilder(
612                     ((OrderedMapNode) configDataNode).getValue(), ((OrderedMapNode) stateDataNode).getValue(), builder);
613
614             return builder.build();
615         } else if (configDataNode instanceof MapNode) {
616             final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
617                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
618
619             mapValueToBuilder(
620                     ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
621
622             return builder.build();
623         } else if (configDataNode instanceof MapEntryNode) {
624             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
625                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
626
627             mapValueToBuilder(
628                     ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
629
630             return builder.build();
631         } else if (configDataNode instanceof ContainerNode) {
632             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder = Builders
633                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
634
635             mapValueToBuilder(
636                     ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
637
638             return builder.build();
639         } else if (configDataNode instanceof AugmentationNode) {
640             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
641                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
642
643             mapValueToBuilder(((AugmentationNode) configDataNode).getValue(),
644                     ((AugmentationNode) stateDataNode).getValue(), builder);
645
646             return builder.build();
647         } else if (configDataNode instanceof ChoiceNode) {
648             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
649                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
650
651             mapValueToBuilder(
652                     ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
653
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());
660
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());
667
668             mapValueToBuilder(((LeafSetNode<Object>) configDataNode).getValue(),
669                     ((LeafSetNode<Object>) stateDataNode).getValue(), builder);
670             return builder.build();
671         } else if (configDataNode instanceof UnkeyedListNode) {
672             final CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> builder = Builders
673                     .unkeyedListBuilder().withNodeIdentifier(((UnkeyedListNode) configDataNode).getIdentifier());
674
675             mapValueToBuilder(((UnkeyedListNode) configDataNode).getValue(),
676                     ((UnkeyedListNode) stateDataNode).getValue(), builder);
677             return builder.build();
678         } else if (configDataNode instanceof UnkeyedListEntryNode) {
679             final DataContainerNodeBuilder<NodeIdentifier, UnkeyedListEntryNode> builder = Builders
680                 .unkeyedListEntryBuilder().withNodeIdentifier(((UnkeyedListEntryNode) configDataNode).getIdentifier());
681
682             mapValueToBuilder(((UnkeyedListEntryNode) configDataNode).getValue(),
683                     ((UnkeyedListEntryNode) stateDataNode).getValue(), builder);
684             return builder.build();
685         } else {
686             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
687         }
688     }
689
690     /**
691      * Map value from container node to builder.
692      *
693      * @param configData
694      *             collection of config data nodes
695      * @param stateData
696      *             collection of state data nodes
697      * @param builder
698      *             builder
699      */
700     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
701             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
702             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
703         final Map<PathArgument, T> configMap = configData.stream().collect(
704                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
705         final Map<PathArgument, T> stateMap = stateData.stream().collect(
706                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
707
708         // merge config and state data of children with different identifiers
709         mapDataToBuilder(configMap, stateMap, builder);
710
711         // merge config and state data of children with the same identifiers
712         mergeDataToBuilder(configMap, stateMap, builder);
713     }
714
715     /**
716      * Map data with different identifiers to builder. Data with different identifiers can be just added
717      * as childs to parent node.
718      *
719      * @param configMap
720      *             map of config data nodes
721      * @param stateMap
722      *             map of state data nodes
723      * @param builder
724      *           - builder
725      */
726     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
727             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
728             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
729         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
730             y -> builder.addChild(y.getValue()));
731         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
732             y -> builder.addChild(y.getValue()));
733     }
734
735     /**
736      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
737      * go one level down with {@code prepareData} method.
738      *
739      * @param configMap
740      *             immutable config data
741      * @param stateMap
742      *             immutable state data
743      * @param builder
744      *           - builder
745      */
746     @SuppressWarnings("unchecked")
747     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
748             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
749             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
750         // it is enough to process only config data because operational contains the same data
751         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
752             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
753     }
754 }