Merge "Fix sonar code smells"
[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.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.UUID;
36 import java.util.stream.Collectors;
37 import javax.validation.Valid;
38 import javax.validation.constraints.NotNull;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
42 import org.onap.cps.ncmp.api.impl.exception.InvalidTopicException;
43 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
44 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
45 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
46 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor;
47 import org.onap.cps.ncmp.rest.mapper.RestOutputCmHandleStateMapper;
48 import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
49 import org.onap.cps.ncmp.rest.model.CmHandleQueryParameters;
50 import org.onap.cps.ncmp.rest.model.RestModuleReference;
51 import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
52 import org.onap.cps.ncmp.rest.model.RestOutputCmHandlePublicProperties;
53 import org.onap.cps.ncmp.rest.util.DeprecationHelper;
54 import org.onap.cps.utils.CpsValidator;
55 import org.onap.cps.utils.JsonObjectMapper;
56 import org.springframework.beans.factory.annotation.Value;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.web.bind.annotation.RequestMapping;
60 import org.springframework.web.bind.annotation.RestController;
61
62 @Slf4j
63 @RestController
64 @RequestMapping("${rest.api.ncmp-base-path}")
65 @RequiredArgsConstructor
66 public class NetworkCmProxyController implements NetworkCmProxyApi {
67
68     private static final String NO_BODY = null;
69     private static final String NO_REQUEST_ID = null;
70     private static final String NO_TOPIC = null;
71     private final NetworkCmProxyDataService networkCmProxyDataService;
72     private final JsonObjectMapper jsonObjectMapper;
73
74     private final DeprecationHelper deprecationHelper;
75     private final NcmpRestInputMapper ncmpRestInputMapper;
76     private final RestOutputCmHandleStateMapper restOutputCmHandleStateMapper;
77     private final CpsNcmpTaskExecutor cpsNcmpTaskExecutor;
78
79     @Value("${notification.async.executor.time-out-value-in-ms:2000}")
80     private int timeOutInMilliSeconds;
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 (isValidTopic(topicParamInQuery)) {
97             final String requestId = UUID.randomUUID().toString();
98             cpsNcmpTaskExecutor.executeTask(() ->
99                 networkCmProxyDataService.getResourceDataOperationalForCmHandle(
100                     cmHandle, resourceIdentifier, optionsParamInQuery, topicParamInQuery,
101                         requestId
102                 ), timeOutInMilliSeconds
103             );
104             return acknowledgeAsyncRequest(requestId);
105         }
106
107         final Object responseObject = networkCmProxyDataService.getResourceDataOperationalForCmHandle(
108             cmHandle, resourceIdentifier, optionsParamInQuery, NO_TOPIC, NO_REQUEST_ID);
109
110         return ResponseEntity.ok(responseObject);
111     }
112
113     /**
114      * Get resource data from pass-through running datastore.
115      *
116      * @param cmHandle cm handle identifier
117      * @param resourceIdentifier resource identifier
118      * @param optionsParamInQuery options query parameter
119      * @param topicParamInQuery topic query parameter
120      * @return {@code ResponseEntity} response from dmi plugin
121      */
122     @Override
123     public ResponseEntity<Object> getResourceDataRunningForCmHandle(final String cmHandle,
124                                                                     final @NotNull @Valid String resourceIdentifier,
125                                                                     final @Valid String optionsParamInQuery,
126                                                                     final @Valid String topicParamInQuery) {
127         if (isValidTopic(topicParamInQuery)) {
128             final String resourceDataRequestId = UUID.randomUUID().toString();
129             cpsNcmpTaskExecutor.executeTask(() ->
130                 networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(
131                     cmHandle, resourceIdentifier, optionsParamInQuery, topicParamInQuery,
132                         resourceDataRequestId
133                 ), timeOutInMilliSeconds
134             );
135             return acknowledgeAsyncRequest(resourceDataRequestId);
136         }
137
138         final Object responseObject = networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(
139             cmHandle, resourceIdentifier, optionsParamInQuery, NO_TOPIC, NO_REQUEST_ID);
140
141         return ResponseEntity.ok(responseObject);
142     }
143
144     @Override
145     public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String resourceIdentifier,
146         final String cmHandle,
147         final Object requestBody, final String contentType) {
148         final Object responseObject = networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
149             resourceIdentifier, PATCH, jsonObjectMapper.asJsonString(requestBody), contentType);
150         return ResponseEntity.ok(responseObject);
151     }
152
153     /**
154      * Create resource data in datastore pass-through running for given cm-handle.
155      *
156      * @param resourceIdentifier resource identifier
157      * @param cmHandle cm handle identifier
158      * @param requestBody the request body
159      * @param contentType content type of body
160      * @return {@code ResponseEntity} response from dmi plugin
161      */
162     @Override
163     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String resourceIdentifier,
164         final String cmHandle, final Object requestBody, final String contentType) {
165         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
166                 resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
167         return new ResponseEntity<>(HttpStatus.CREATED);
168     }
169
170     /**
171      * Update resource data in datastore pass-through running for given cm-handle.
172      *
173      * @param resourceIdentifier resource identifier
174      * @param cmHandle cm handle identifier
175      * @param requestBody the request body
176      * @param contentType content type of the body
177      * @return response entity
178      */
179     @Override
180     public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String resourceIdentifier,
181                                                                        final String cmHandle,
182                                                                        final Object requestBody,
183                                                                        final String contentType) {
184         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
185                 resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
186         return new ResponseEntity<>(HttpStatus.OK);
187     }
188
189
190     /**
191      *  Delete resource data in datastore pass-through running for a given cm-handle.
192      *
193      * @param resourceIdentifier resource identifier
194      * @param cmHandle cm handle identifier
195      * @param contentType content type of the body
196      * @return response entity no content if request is successful
197      */
198     @Override
199     public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String cmHandle,
200                                                                      final String resourceIdentifier,
201                                                                      final String contentType) {
202         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
203             resourceIdentifier, DELETE, NO_BODY, contentType);
204         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
205     }
206
207     /**
208      * Query and return cm handles that match the given query parameters.
209      *
210      * @param cmHandleQueryParameters the cm handle query parameters
211      * @return collection of cm handles
212      */
213     @Override
214     public ResponseEntity<List<RestOutputCmHandle>> searchCmHandles(
215             final CmHandleQueryParameters cmHandleQueryParameters) {
216         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
217                 deprecationHelper.mapOldConditionProperties(cmHandleQueryParameters);
218         final Set<NcmpServiceCmHandle> cmHandles = networkCmProxyDataService
219                 .executeCmHandleSearch(cmHandleQueryApiParameters);
220         final List<RestOutputCmHandle> outputCmHandles =
221                 cmHandles.stream().map(this::toRestOutputCmHandle).collect(Collectors.toList());
222         return ResponseEntity.ok(outputCmHandles);
223     }
224
225     /**
226      * Query and return cm handle ids that match the given query parameters.
227      *
228      * @param cmHandleQueryParameters the cm handle query parameters
229      * @return collection of cm handle ids
230      */
231     @Override
232     public ResponseEntity<List<String>> searchCmHandleIds(
233         final CmHandleQueryParameters cmHandleQueryParameters) {
234         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
235                 jsonObjectMapper.convertToValueType(cmHandleQueryParameters, CmHandleQueryApiParameters.class);
236         final Set<String> cmHandleIds = networkCmProxyDataService.executeCmHandleIdSearch(cmHandleQueryApiParameters);
237         return ResponseEntity.ok(List.copyOf(cmHandleIds));
238     }
239
240     /**
241      * Search for Cm Handle and Properties by Name.
242      * @param cmHandleId cm-handle identifier
243      * @return cm handle and its properties
244      */
245     @Override
246     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
247         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
248         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
249         return ResponseEntity.ok(restOutputCmHandle);
250     }
251
252     /**
253      * Get Cm Handle Properties by Cm Handle Id.
254      * @param cmHandleId cm-handle identifier
255      * @return cm handle and its properties
256      */
257     @Override
258     public ResponseEntity<RestOutputCmHandlePublicProperties> getCmHandlePublicPropertiesByCmHandleId(
259         final String cmHandleId) {
260         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
261         cmHandlePublicProperties.add(networkCmProxyDataService.getCmHandlePublicProperties(cmHandleId));
262         final RestOutputCmHandlePublicProperties restOutputCmHandlePublicProperties =
263             new RestOutputCmHandlePublicProperties();
264         restOutputCmHandlePublicProperties.setPublicCmHandleProperties(cmHandlePublicProperties);
265         return ResponseEntity.ok(restOutputCmHandlePublicProperties);
266     }
267
268     /**
269      * Return module references for a cm handle.
270      *
271      * @param cmHandle the cm handle
272      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
273      */
274     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
275         final List<RestModuleReference> restModuleReferences =
276             networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
277             .map(ncmpRestInputMapper::toRestModuleReference)
278                 .collect(Collectors.toList());
279         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
280     }
281
282     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
283         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
284         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
285         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
286         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
287         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
288         restOutputCmHandle.setState(restOutputCmHandleStateMapper.toRestOutputCmHandleState(
289                 ncmpServiceCmHandle.getCompositeState()));
290         return restOutputCmHandle;
291     }
292
293     private static boolean isValidTopic(final String topicName) {
294         if (topicName == null) {
295             return false;
296         }
297         if (CpsValidator.validateTopicName(topicName)) {
298             return true;
299         }
300         throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
301     }
302
303     private ResponseEntity<Object> acknowledgeAsyncRequest(final String requestId) {
304         final Map<String, Object> acknowledgeData = new HashMap<>(1);
305         acknowledgeData.put("requestId", requestId);
306         return ResponseEntity.ok(acknowledgeData);
307     }
308
309 }
310