Kafka consumer can not be turned off
[cps.git] / cps-ncmp-rest / src / main / java / org / onap / cps / ncmp / rest / controller / NetworkCmProxyController.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Modifications Copyright (C) 2021-2022 Nordix Foundation
5  *  Modifications Copyright (C) 2021 highstreet technologies GmbH
6  *  Modifications Copyright (C) 2021-2022 Bell Canada
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.ncmp.rest.controller;
25
26 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE;
27 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE;
28 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH;
29 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE;
30
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.UUID;
35 import java.util.stream.Collectors;
36 import javax.validation.Valid;
37 import javax.validation.constraints.NotNull;
38 import lombok.RequiredArgsConstructor;
39 import lombok.extern.slf4j.Slf4j;
40 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
41 import org.onap.cps.ncmp.api.impl.exception.InvalidTopicException;
42 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
43 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
44 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
45 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor;
46 import org.onap.cps.ncmp.rest.mapper.RestOutputCmHandleStateMapper;
47 import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
48 import org.onap.cps.ncmp.rest.model.CmHandleQueryParameters;
49 import org.onap.cps.ncmp.rest.model.RestModuleReference;
50 import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
51 import org.onap.cps.ncmp.rest.model.RestOutputCmHandlePublicProperties;
52 import org.onap.cps.ncmp.rest.util.DeprecationHelper;
53 import org.onap.cps.utils.CpsValidator;
54 import org.onap.cps.utils.JsonObjectMapper;
55 import org.springframework.beans.factory.annotation.Value;
56 import org.springframework.http.HttpStatus;
57 import org.springframework.http.ResponseEntity;
58 import org.springframework.web.bind.annotation.RequestMapping;
59 import org.springframework.web.bind.annotation.RestController;
60
61 @Slf4j
62 @RestController
63 @RequestMapping("${rest.api.ncmp-base-path}")
64 @RequiredArgsConstructor
65 public class NetworkCmProxyController implements NetworkCmProxyApi {
66
67     private static final String NO_BODY = null;
68     private static final String NO_REQUEST_ID = null;
69     private static final String NO_TOPIC = null;
70     private final NetworkCmProxyDataService networkCmProxyDataService;
71     private final JsonObjectMapper jsonObjectMapper;
72
73     private final DeprecationHelper deprecationHelper;
74     private final NcmpRestInputMapper ncmpRestInputMapper;
75     private final RestOutputCmHandleStateMapper restOutputCmHandleStateMapper;
76     private final CpsNcmpTaskExecutor cpsNcmpTaskExecutor;
77     @Value("${notification.async.executor.time-out-value-in-ms:2000}")
78     private int timeOutInMilliSeconds;
79     @Value("${notification.enabled:true}")
80     private boolean asyncEnabled;
81
82     /**
83      * Get resource data from operational datastore.
84      *
85      * @param cmHandle cm handle identifier
86      * @param resourceIdentifier resource identifier
87      * @param optionsParamInQuery options query parameter
88      * @param topicParamInQuery topic query parameter
89      * @return {@code ResponseEntity} response from dmi plugin
90      */
91     @Override
92     public ResponseEntity<Object> getResourceDataOperationalForCmHandle(final String cmHandle,
93                                                                         final @NotNull @Valid String resourceIdentifier,
94                                                                         final @Valid String optionsParamInQuery,
95                                                                         final @Valid String topicParamInQuery) {
96         if (asyncEnabled && isValidTopic(topicParamInQuery)) {
97             final String requestId = UUID.randomUUID().toString();
98             log.info("Received Async passthrough-operational request with id {}", requestId);
99             cpsNcmpTaskExecutor.executeTask(() ->
100                     networkCmProxyDataService.getResourceDataOperationalForCmHandle(
101                         cmHandle, resourceIdentifier, optionsParamInQuery, topicParamInQuery, requestId
102                     ), timeOutInMilliSeconds
103             );
104             return ResponseEntity.ok(Map.of("requestId", requestId));
105         } else {
106             log.warn("Asynchronous messaging is currently disabled for passthrough-operational."
107                 + " Will use synchronous operation.");
108         }
109
110         final Object responseObject = networkCmProxyDataService.getResourceDataOperationalForCmHandle(
111             cmHandle, resourceIdentifier, optionsParamInQuery, NO_TOPIC, NO_REQUEST_ID);
112
113         return ResponseEntity.ok(responseObject);
114     }
115
116     /**
117      * Get resource data from pass-through running datastore.
118      *
119      * @param cmHandle cm handle identifier
120      * @param resourceIdentifier resource identifier
121      * @param optionsParamInQuery options query parameter
122      * @param topicParamInQuery topic query parameter
123      * @return {@code ResponseEntity} response from dmi plugin
124      */
125     @Override
126     public ResponseEntity<Object> getResourceDataRunningForCmHandle(final String cmHandle,
127                                                                     final @NotNull @Valid String resourceIdentifier,
128                                                                     final @Valid String optionsParamInQuery,
129                                                                     final @Valid String topicParamInQuery) {
130         if (asyncEnabled && isValidTopic(topicParamInQuery)) {
131             final String requestId = UUID.randomUUID().toString();
132             log.info("Received Async passthrough-running request with id {}", requestId);
133             cpsNcmpTaskExecutor.executeTask(() ->
134                 networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(
135                     cmHandle, resourceIdentifier, optionsParamInQuery, topicParamInQuery, requestId
136                 ), timeOutInMilliSeconds
137             );
138             return ResponseEntity.ok(Map.of("requestId", requestId));
139         } else {
140             log.warn("Asynchronous messaging is currently disabled for passthrough-running."
141                 + " Will use synchronous operation.");
142         }
143
144         final Object responseObject = networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(
145             cmHandle, resourceIdentifier, optionsParamInQuery, NO_TOPIC, NO_REQUEST_ID);
146
147         return ResponseEntity.ok(responseObject);
148     }
149
150     @Override
151     public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String resourceIdentifier,
152         final String cmHandle,
153         final Object requestBody, final String contentType) {
154         final Object responseObject = networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
155             resourceIdentifier, PATCH, jsonObjectMapper.asJsonString(requestBody), contentType);
156         return ResponseEntity.ok(responseObject);
157     }
158
159     /**
160      * Create resource data in datastore pass-through running for given cm-handle.
161      *
162      * @param resourceIdentifier resource identifier
163      * @param cmHandle cm handle identifier
164      * @param requestBody the request body
165      * @param contentType content type of body
166      * @return {@code ResponseEntity} response from dmi plugin
167      */
168     @Override
169     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String resourceIdentifier,
170         final String cmHandle, final Object requestBody, final String contentType) {
171         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
172                 resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
173         return new ResponseEntity<>(HttpStatus.CREATED);
174     }
175
176     /**
177      * Update resource data in datastore pass-through running for given cm-handle.
178      *
179      * @param resourceIdentifier resource identifier
180      * @param cmHandle cm handle identifier
181      * @param requestBody the request body
182      * @param contentType content type of the body
183      * @return response entity
184      */
185     @Override
186     public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String resourceIdentifier,
187                                                                        final String cmHandle,
188                                                                        final Object requestBody,
189                                                                        final String contentType) {
190         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
191                 resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
192         return new ResponseEntity<>(HttpStatus.OK);
193     }
194
195
196     /**
197      *  Delete resource data in datastore pass-through running for a given cm-handle.
198      *
199      * @param resourceIdentifier resource identifier
200      * @param cmHandle cm handle identifier
201      * @param contentType content type of the body
202      * @return response entity no content if request is successful
203      */
204     @Override
205     public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String cmHandle,
206                                                                      final String resourceIdentifier,
207                                                                      final String contentType) {
208         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
209             resourceIdentifier, DELETE, NO_BODY, contentType);
210         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
211     }
212
213     /**
214      * Query and return cm handles that match the given query parameters.
215      *
216      * @param cmHandleQueryParameters the cm handle query parameters
217      * @return collection of cm handles
218      */
219     @Override
220     @SuppressWarnings("deprecation") // mapOldConditionProperties method will be removed in Release 12
221     public ResponseEntity<List<RestOutputCmHandle>> searchCmHandles(
222             final CmHandleQueryParameters cmHandleQueryParameters) {
223         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
224                 deprecationHelper.mapOldConditionProperties(cmHandleQueryParameters);
225         final Set<NcmpServiceCmHandle> cmHandles = networkCmProxyDataService
226                 .executeCmHandleSearch(cmHandleQueryApiParameters);
227         final List<RestOutputCmHandle> outputCmHandles =
228                 cmHandles.stream().map(this::toRestOutputCmHandle).collect(Collectors.toList());
229         return ResponseEntity.ok(outputCmHandles);
230     }
231
232     /**
233      * Query and return cm handle ids that match the given query parameters.
234      *
235      * @param cmHandleQueryParameters the cm handle query parameters
236      * @return collection of cm handle ids
237      */
238     @Override
239     public ResponseEntity<List<String>> searchCmHandleIds(
240         final CmHandleQueryParameters cmHandleQueryParameters) {
241         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
242                 jsonObjectMapper.convertToValueType(cmHandleQueryParameters, CmHandleQueryApiParameters.class);
243         final Set<String> cmHandleIds = networkCmProxyDataService.executeCmHandleIdSearch(cmHandleQueryApiParameters);
244         return ResponseEntity.ok(List.copyOf(cmHandleIds));
245     }
246
247     /**
248      * Search for Cm Handle and Properties by Name.
249      * @param cmHandleId cm-handle identifier
250      * @return cm handle and its properties
251      */
252     @Override
253     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
254         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
255         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
256         return ResponseEntity.ok(restOutputCmHandle);
257     }
258
259     /**
260      * Get Cm Handle Properties by Cm Handle Id.
261      * @param cmHandleId cm-handle identifier
262      * @return cm handle and its properties
263      */
264     @Override
265     public ResponseEntity<RestOutputCmHandlePublicProperties> getCmHandlePublicPropertiesByCmHandleId(
266         final String cmHandleId) {
267         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
268         cmHandlePublicProperties.add(networkCmProxyDataService.getCmHandlePublicProperties(cmHandleId));
269         final RestOutputCmHandlePublicProperties restOutputCmHandlePublicProperties =
270             new RestOutputCmHandlePublicProperties();
271         restOutputCmHandlePublicProperties.setPublicCmHandleProperties(cmHandlePublicProperties);
272         return ResponseEntity.ok(restOutputCmHandlePublicProperties);
273     }
274
275     /**
276      * Return module references for a cm handle.
277      *
278      * @param cmHandle the cm handle
279      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
280      */
281     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
282         final List<RestModuleReference> restModuleReferences =
283             networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
284             .map(ncmpRestInputMapper::toRestModuleReference)
285                 .collect(Collectors.toList());
286         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
287     }
288
289     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
290         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
291         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
292         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
293         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
294         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
295         restOutputCmHandle.setState(restOutputCmHandleStateMapper.toRestOutputCmHandleState(
296                 ncmpServiceCmHandle.getCompositeState()));
297         return restOutputCmHandle;
298     }
299
300     private static boolean isValidTopic(final String topicName) {
301         if (topicName == null) {
302             return false;
303         }
304         if (CpsValidator.validateTopicName(topicName)) {
305             return true;
306         }
307         throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
308     }
309
310 }
311