Refactor datatrore handling in API requests
[cps.git] / cps-ncmp-rest / src / main / java / org / onap / cps / ncmp / rest / controller / handlers / NcmpDatastoreRequestHandler.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.rest.controller.handlers;
22
23 import java.util.List;
24 import java.util.Map;
25 import java.util.UUID;
26 import java.util.function.Supplier;
27 import lombok.RequiredArgsConstructor;
28 import lombok.extern.slf4j.Slf4j;
29 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor;
30 import org.onap.cps.ncmp.rest.util.TopicValidator;
31 import org.springframework.beans.factory.annotation.Value;
32 import org.springframework.http.HttpStatus;
33 import org.springframework.http.ResponseEntity;
34 import org.springframework.stereotype.Service;
35
36 @Slf4j
37 @Service
38 @RequiredArgsConstructor
39 public class NcmpDatastoreRequestHandler implements TaskManagementDefaultHandler {
40
41     @Value("${notification.async.executor.time-out-value-in-ms:2000}")
42     protected int timeOutInMilliSeconds;
43
44     @Value("${notification.enabled:true}")
45     protected boolean notificationFeatureEnabled;
46
47     private final CpsNcmpTaskExecutor cpsNcmpTaskExecutor;
48
49     /**
50      * Executes synchronous/asynchronous request for given cm handle.
51      *
52      * @param datastoreName       the name of the datastore
53      * @param cmHandleId          the cm handle
54      * @param resourceIdentifier  the resource identifier
55      * @param optionsParamInQuery the options param in query
56      * @param topicParamInQuery   the topic param in query
57      * @param includeDescendants  whether include descendants
58      * @return the response entity
59      */
60     public ResponseEntity<Object> executeRequest(final String datastoreName,
61                                                  final String cmHandleId,
62                                                  final String resourceIdentifier,
63                                                  final String optionsParamInQuery,
64                                                  final String topicParamInQuery,
65                                                  final boolean includeDescendants) {
66
67         final boolean asyncResponseRequested = topicParamInQuery != null;
68         if (asyncResponseRequested && notificationFeatureEnabled) {
69             return executeAsyncTaskAndGetResponseEntity(datastoreName, cmHandleId, resourceIdentifier,
70                 optionsParamInQuery, topicParamInQuery, includeDescendants, false);
71         }
72
73         if (asyncResponseRequested) {
74             log.warn("Asynchronous request is unavailable as notification feature is currently disabled, "
75                     + "will use synchronous operation.");
76         }
77         final Supplier<Object> taskSupplier = getTaskSupplierForGetRequest(datastoreName, cmHandleId,
78                 resourceIdentifier, optionsParamInQuery, NO_TOPIC, NO_REQUEST_ID, includeDescendants);
79         return executeTaskSync(taskSupplier);
80     }
81
82     /**
83      * Executes a synchronous request for given cm handle.
84      * Note. Currently only ncmp-datastore:operational supports query operations.
85      *
86      * @param cmHandleId         the cm handle
87      * @param resourceIdentifier the resource identifier
88      * @param includeDescendants whether include descendants
89      * @return the response entity
90      */
91     public ResponseEntity<Object> executeRequest(final String cmHandleId,
92                                                  final String resourceIdentifier,
93                                                  final boolean includeDescendants) {
94
95         final Supplier<Object> taskSupplier = getTaskSupplierForQueryRequest(cmHandleId, resourceIdentifier,
96                 includeDescendants);
97         return executeTaskSync(taskSupplier);
98     }
99
100     /**
101      * Executes synchronous/asynchronous request for batch of cm handles.
102      *
103      * @param datastoreName       the name of the datastore
104      * @param cmHandleIds         list of cm handles
105      * @param resourceIdentifier  the resource identifier
106      * @param optionsParamInQuery the options param in query
107      * @param topicParamInQuery   the topic param in query
108      * @param includeDescendants  whether to include descendants or not
109      * @return the response entity
110      */
111     public ResponseEntity<Object> executeRequest(final String datastoreName,
112                                                  final List<String> cmHandleIds,
113                                                  final String resourceIdentifier,
114                                                  final String optionsParamInQuery,
115                                                  final String topicParamInQuery,
116                                                  final boolean includeDescendants) {
117
118         return executeAsyncTaskAndGetResponseEntity(datastoreName, cmHandleIds, resourceIdentifier, optionsParamInQuery,
119                 topicParamInQuery, includeDescendants, true);
120
121     }
122
123     protected ResponseEntity<Object> executeTaskAsync(final String topicParamInQuery,
124                                                       final String requestId,
125                                                       final Supplier<Object> taskSupplier) {
126
127         TopicValidator.validateTopicName(topicParamInQuery);
128         log.debug("Received Async request with id {}", requestId);
129         cpsNcmpTaskExecutor.executeTask(taskSupplier, timeOutInMilliSeconds);
130
131         return ResponseEntity.ok(Map.of("requestId", requestId));
132     }
133
134     protected ResponseEntity<Object> executeTaskSync(final Supplier<Object> taskSupplier) {
135         return ResponseEntity.ok(taskSupplier.get());
136     }
137
138     private ResponseEntity<Object> executeAsyncTaskAndGetResponseEntity(final String datastoreName,
139                                                                         final Object targetObject,
140                                                                         final String resourceIdentifier,
141                                                                         final String optionsParamInQuery,
142                                                                         final String topicParamInQuery,
143                                                                         final boolean includeDescendants,
144                                                                         final boolean isBulkRequest) {
145         final String requestId = UUID.randomUUID().toString();
146         final Supplier<Object> taskSupplier;
147         if (isBulkRequest) {
148             taskSupplier = getTaskSupplierForBulkRequest(datastoreName, (List<String>) targetObject,
149                     resourceIdentifier, optionsParamInQuery, topicParamInQuery, requestId, includeDescendants);
150         } else {
151             taskSupplier = getTaskSupplierForGetRequest(datastoreName, targetObject.toString(), resourceIdentifier,
152                     optionsParamInQuery, topicParamInQuery, requestId, includeDescendants);
153         }
154         if (taskSupplier == NO_OBJECT_SUPPLIER) {
155             return new ResponseEntity<>(Map.of("status", "Unable to execute request as "
156                     + "datastore is not implemented."), HttpStatus.NOT_IMPLEMENTED);
157         }
158         return executeTaskAsync(topicParamInQuery, requestId, taskSupplier);
159     }
160 }