Bug 7172 - Correct error-info for missing-attribute errors
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / restful / 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.restful.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import java.util.Collection;
13 import java.util.Map;
14 import java.util.function.Function;
15 import java.util.stream.Collectors;
16 import javax.annotation.Nonnull;
17 import javax.annotation.Nullable;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
20 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
21 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
22 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
23 import org.opendaylight.restconf.restful.transaction.TransactionVarsWrapper;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
37 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
38 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43
44 /**
45  * Util class for read data from data store via transaction.
46  * <ul>
47  * <li>config
48  * <li>state
49  * <li>all (config + state)
50  * </ul>
51  *
52  */
53 public final class ReadDataTransactionUtil {
54
55     private ReadDataTransactionUtil() {
56         throw new UnsupportedOperationException("Util class.");
57     }
58
59     /**
60      * Read specific type of data from data store via transaction.
61      *
62      * @param valueOfContent
63      *            - type of data to read (config, state, all)
64      * @param transactionNode
65      *            - {@link TransactionVarsWrapper} - wrapper for variables
66      * @return {@link NormalizedNode}
67      */
68     public static @Nullable NormalizedNode<?, ?> readData(@Nullable final String valueOfContent,
69                                                           @Nonnull final TransactionVarsWrapper transactionNode) {
70         final NormalizedNode<?, ?> data;
71         if (valueOfContent != null) {
72             switch (valueOfContent) {
73                 case RestconfDataServiceConstant.ReadData.CONFIG:
74                     transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
75                     data = readDataViaTransaction(transactionNode);
76                     break;
77                 case RestconfDataServiceConstant.ReadData.NONCONFIG:
78                     transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
79                     data = readDataViaTransaction(transactionNode);
80                     break;
81                 case RestconfDataServiceConstant.ReadData.ALL:
82                     data = readAllData(transactionNode);
83                     break;
84                 default:
85                     throw new RestconfDocumentedException("Bad query parameter for content.", ErrorType.APPLICATION,
86                             ErrorTag.INVALID_VALUE);
87             }
88         } else {
89             data = readAllData(transactionNode);
90         }
91
92         return data;
93     }
94
95     /**
96      * If is set specific {@link LogicalDatastoreType} in
97      * {@link TransactionVarsWrapper}, then read this type of data from DS. If
98      * don't, we have to read all data from DS (state + config)
99      *
100      * @param transactionNode
101      *            - {@link TransactionVarsWrapper} - wrapper for variables
102      * @return {@link NormalizedNode}
103      */
104     private static @Nullable NormalizedNode<?, ?> readDataViaTransaction(
105             @Nonnull final TransactionVarsWrapper transactionNode) {
106         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> listenableFuture = transactionNode
107                 .getTransactionChain().newReadOnlyTransaction().read(transactionNode.getLogicalDatastoreType(),
108                         transactionNode.getInstanceIdentifier().getInstanceIdentifier());
109         final NormalizedNodeFactory dataFactory = new NormalizedNodeFactory();
110         FutureCallbackTx.addCallback(listenableFuture, RestconfDataServiceConstant.ReadData.READ_TYPE_TX,
111                 dataFactory);
112         return dataFactory.build();
113     }
114
115     /**
116      * Read config and state data, then map them.
117      *
118      * @param transactionNode
119      *            - {@link TransactionVarsWrapper} - wrapper for variables
120      * @return {@link NormalizedNode}
121      */
122     private static @Nullable NormalizedNode<?, ?> readAllData(@Nonnull final TransactionVarsWrapper transactionNode) {
123         // PREPARE STATE DATA NODE
124         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.OPERATIONAL);
125         final NormalizedNode<?, ?> stateDataNode = readDataViaTransaction(transactionNode);
126
127         // PREPARE CONFIG DATA NODE
128         transactionNode.setLogicalDatastoreType(LogicalDatastoreType.CONFIGURATION);
129         final NormalizedNode<?, ?> configDataNode = readDataViaTransaction(transactionNode);
130
131         // if no data exists
132         if ((stateDataNode == null) && (configDataNode == null)) {
133             return null;
134         }
135
136         // return config data
137         if (stateDataNode == null) {
138             return configDataNode;
139         }
140
141         // return state data
142         if (configDataNode == null) {
143             return stateDataNode;
144         }
145
146         // merge data from config and state
147         return mapNode(stateDataNode, configDataNode);
148     }
149
150     /**
151      * Map data by type of read node.
152      *
153      * @param stateDataNode
154      *            - data node of state data
155      * @param configDataNode
156      *            - data node of config data
157      * @return {@link NormalizedNode}
158      */
159     private static @Nonnull NormalizedNode<?, ?> mapNode(@Nonnull final NormalizedNode<?, ?> stateDataNode,
160                                                          @Nonnull final NormalizedNode<?, ?> configDataNode) {
161         validPossibilityOfMergeNodes(stateDataNode, configDataNode);
162         if (configDataNode instanceof RpcDefinition) {
163             return prepareRpcData(configDataNode, stateDataNode);
164         } else {
165             return prepareData(configDataNode, stateDataNode);
166         }
167     }
168
169     /**
170      * Valid of can be data merged together.
171      *
172      * @param stateDataNode
173      *            - data node of state data
174      * @param configDataNode
175      *            - data node of config data
176      */
177     private static void validPossibilityOfMergeNodes(@Nonnull final NormalizedNode<?, ?> stateDataNode,
178                                                      @Nonnull final NormalizedNode<?, ?> configDataNode) {
179         final QNameModule moduleOfStateData = stateDataNode.getIdentifier().getNodeType().getModule();
180         final QNameModule moduleOfConfigData = configDataNode.getIdentifier().getNodeType().getModule();
181         if (moduleOfStateData != moduleOfConfigData) {
182             throw new RestconfDocumentedException("It is not possible to merge ");
183         }
184     }
185
186     /**
187      * Prepare and map data for rpc
188      *
189      * @param configDataNode
190      *            - data node of config data
191      * @param stateDataNode
192      *            - data node of state data
193      * @return {@link NormalizedNode}
194      */
195     private static @Nonnull NormalizedNode<?, ?> prepareRpcData(@Nonnull final NormalizedNode<?, ?> configDataNode,
196                                                                 @Nonnull final NormalizedNode<?, ?> stateDataNode) {
197         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder = ImmutableNodes
198                 .mapEntryBuilder();
199         mapEntryBuilder.withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.getIdentifier());
200
201         // MAP CONFIG DATA
202         mapRpcDataNode(configDataNode, mapEntryBuilder);
203         // MAP STATE DATA
204         mapRpcDataNode(stateDataNode, mapEntryBuilder);
205
206         return ImmutableNodes.mapNodeBuilder(configDataNode.getNodeType()).addChild(mapEntryBuilder.build()).build();
207     }
208
209     /**
210      * Map node to map entry builder.
211      *
212      * @param dataNode
213      *            - data node
214      * @param mapEntryBuilder
215      *            - builder for mapping data
216      */
217     private static void mapRpcDataNode(@Nonnull final NormalizedNode<?, ?> dataNode,
218                                        @Nonnull final DataContainerNodeBuilder<
219                                                NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
220         ((ContainerNode) dataNode).getValue().forEach(mapEntryBuilder::addChild);
221     }
222
223     /**
224      * Prepare and map all data from DS
225      *
226      * @param configDataNode
227      *            - data node of config data
228      * @param stateDataNode
229      *            - data node of state data
230      * @return {@link NormalizedNode}
231      */
232     private static @Nonnull NormalizedNode<?, ?> prepareData(@Nonnull final NormalizedNode<?, ?> configDataNode,
233                                                              @Nonnull final NormalizedNode<?, ?> stateDataNode) {
234         if (configDataNode instanceof MapNode) {
235             final CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableNodes
236                     .mapNodeBuilder().withNodeIdentifier(((MapNode) configDataNode).getIdentifier());
237
238             mapValueToBuilder(
239                     ((MapNode) configDataNode).getValue(), ((MapNode) stateDataNode).getValue(), builder);
240
241             return builder.build();
242         } else if (configDataNode instanceof MapEntryNode) {
243             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder = ImmutableNodes
244                     .mapEntryBuilder().withNodeIdentifier(((MapEntryNode) configDataNode).getIdentifier());
245
246             mapValueToBuilder(
247                     ((MapEntryNode) configDataNode).getValue(), ((MapEntryNode) stateDataNode).getValue(), builder);
248
249             return builder.build();
250         } else if (configDataNode instanceof ContainerNode) {
251             final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders
252                     .containerBuilder().withNodeIdentifier(((ContainerNode) configDataNode).getIdentifier());
253
254             mapValueToBuilder(
255                     ((ContainerNode) configDataNode).getValue(), ((ContainerNode) stateDataNode).getValue(), builder);
256
257             return builder.build();
258         } else if (configDataNode instanceof AugmentationNode) {
259             final DataContainerNodeBuilder<AugmentationIdentifier, AugmentationNode> builder = Builders
260                     .augmentationBuilder().withNodeIdentifier(((AugmentationNode) configDataNode).getIdentifier());
261
262             mapValueToBuilder(
263                     ((AugmentationNode) configDataNode).getValue(), ((AugmentationNode) stateDataNode).getValue(), builder);
264
265             return builder.build();
266         } else if (configDataNode instanceof ChoiceNode) {
267             final DataContainerNodeBuilder<NodeIdentifier, ChoiceNode> builder = Builders
268                     .choiceBuilder().withNodeIdentifier(((ChoiceNode) configDataNode).getIdentifier());
269
270             mapValueToBuilder(
271                     ((ChoiceNode) configDataNode).getValue(), ((ChoiceNode) stateDataNode).getValue(), builder);
272
273             return builder.build();
274         } else if (configDataNode instanceof LeafNode) {
275             return ImmutableNodes.leafNode(configDataNode.getNodeType(), configDataNode.getValue());
276         } else {
277             throw new RestconfDocumentedException("Bad type of node.");
278         }
279     }
280
281     /**
282      * Map value from container node to builder.
283      *
284      * @param configData
285      *            - collection of config data nodes
286      * @param stateData
287      *            - collection of state data nodes
288      * @param builder
289      *            - builder
290      */
291     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapValueToBuilder(
292             @Nonnull final Collection<T> configData,
293             @Nonnull final Collection<T> stateData,
294             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
295         final Map<PathArgument, T> configMap = configData.stream().collect(
296                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
297         final Map<PathArgument, T> stateMap = stateData.stream().collect(
298                 Collectors.toMap(NormalizedNode::getIdentifier, Function.identity()));
299
300         // merge config and state data of children with different identifiers
301         mapDataToBuilder(configMap, stateMap, builder);
302
303         // merge config and state data of children with the same identifiers
304         mergeDataToBuilder(configMap, stateMap, builder);
305     }
306
307     /**
308      * Map data with different identifiers to builder. Data with different identifiers can be just added
309      * as childs to parent node.
310      *
311      * @param configMap
312      *            - map of config data nodes
313      * @param stateMap
314      *            - map of state data nodes
315      * @param builder
316      *           - builder
317      */
318     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mapDataToBuilder(
319             @Nonnull final Map<PathArgument, T> configMap,
320             @Nonnull final Map<PathArgument, T> stateMap,
321             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
322         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
323                 y -> builder.addChild(y.getValue()));
324         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
325                 y -> builder.addChild(y.getValue()));
326     }
327
328     /**
329      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
330      * go one level down with {@code prepareData} method.
331      *
332      * @param configMap
333      *            - immutable config data
334      * @param stateMap
335      *            - immutable state data
336      * @param builder
337      *           - builder
338      */
339     @SuppressWarnings("unchecked")
340     private static <T extends NormalizedNode<? extends PathArgument, ?>> void mergeDataToBuilder(
341             @Nonnull final Map<PathArgument, T> configMap,
342             @Nonnull final Map<PathArgument, T> stateMap,
343             @Nonnull final NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
344         // it is enough to process only config data because operational contains the same data
345         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
346                 y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
347     }
348 }