Refactoring/ Adding Tests for Validation
[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  *  Modification Copyright (C) 2021 highstreet technologies GmbH
6  *  Modifications (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.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.UUID;
39 import java.util.stream.Collectors;
40 import javax.validation.Valid;
41 import javax.validation.constraints.NotNull;
42 import lombok.RequiredArgsConstructor;
43 import lombok.extern.slf4j.Slf4j;
44 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
45 import org.onap.cps.ncmp.api.impl.exception.InvalidTopicException;
46 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
47 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
48 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
49 import org.onap.cps.ncmp.rest.model.CmHandleProperties;
50 import org.onap.cps.ncmp.rest.model.CmHandleProperty;
51 import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
52 import org.onap.cps.ncmp.rest.model.CmHandleQueryRestParameters;
53 import org.onap.cps.ncmp.rest.model.CmHandles;
54 import org.onap.cps.ncmp.rest.model.ConditionProperties;
55 import org.onap.cps.ncmp.rest.model.Conditions;
56 import org.onap.cps.ncmp.rest.model.ModuleNameAsJsonObject;
57 import org.onap.cps.ncmp.rest.model.ModuleNamesAsJsonArray;
58 import org.onap.cps.ncmp.rest.model.RestModuleReference;
59 import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
60 import org.onap.cps.utils.CpsValidator;
61 import org.onap.cps.utils.JsonObjectMapper;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.http.ResponseEntity;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RestController;
66
67 @Slf4j
68 @RestController
69 @RequestMapping("${rest.api.ncmp-base-path}")
70 @RequiredArgsConstructor
71 public class NetworkCmProxyController implements NetworkCmProxyApi {
72
73     private static final String NO_BODY = null;
74     private static final String NO_REQUEST_ID = null;
75     private static final String NO_TOPIC = null;
76     public static final String ASYNC_REQUEST_ID = "requestId";
77
78     private final NetworkCmProxyDataService networkCmProxyDataService;
79     private final JsonObjectMapper jsonObjectMapper;
80     private final NcmpRestInputMapper ncmpRestInputMapper;
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         final ResponseEntity<Map<String, Object>> asyncResponse = populateAsyncResponse(topicParamInQuery);
97         final Map<String, Object> asyncResponseData = asyncResponse.getBody();
98
99         final Object responseObject = networkCmProxyDataService.getResourceDataOperationalForCmHandle(cmHandle,
100                 resourceIdentifier,
101                 optionsParamInQuery,
102                 asyncResponseData == null ? NO_TOPIC : topicParamInQuery,
103                 asyncResponseData == null ? NO_REQUEST_ID : asyncResponseData.get(ASYNC_REQUEST_ID).toString());
104
105         if (asyncResponseData == null) {
106             return ResponseEntity.ok(responseObject);
107         }
108         return ResponseEntity.ok(asyncResponse);
109     }
110
111     /**
112      * Get resource data from pass-through running datastore.
113      *
114      * @param cmHandle cm handle identifier
115      * @param resourceIdentifier resource identifier
116      * @param optionsParamInQuery options query parameter
117      * @param topicParamInQuery topic query parameter
118      * @return {@code ResponseEntity} response from dmi plugin
119      */
120     @Override
121     public ResponseEntity<Object> getResourceDataRunningForCmHandle(final String cmHandle,
122                                                                     final @NotNull @Valid String resourceIdentifier,
123                                                                     final @Valid String optionsParamInQuery,
124                                                                     final @Valid String topicParamInQuery) {
125         final ResponseEntity<Map<String, Object>> asyncResponse = populateAsyncResponse(topicParamInQuery);
126         final Map<String, Object> asyncResponseData = asyncResponse.getBody();
127
128         final Object responseObject = networkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle(cmHandle,
129                 resourceIdentifier,
130                 optionsParamInQuery,
131                 asyncResponseData == null ? NO_TOPIC : topicParamInQuery,
132                 asyncResponseData == null ? NO_REQUEST_ID : asyncResponseData.get(ASYNC_REQUEST_ID).toString());
133
134         if (asyncResponseData == null) {
135             return ResponseEntity.ok(responseObject);
136         }
137         return ResponseEntity.ok(asyncResponse);
138     }
139
140     @Override
141     public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String resourceIdentifier,
142         final String cmHandle,
143         final Object requestBody, final String contentType) {
144         final Object responseObject = networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
145             resourceIdentifier, PATCH, jsonObjectMapper.asJsonString(requestBody), contentType);
146         return ResponseEntity.ok(responseObject);
147     }
148
149     /**
150      * Create resource data in datastore pass-through running for given cm-handle.
151      *
152      * @param resourceIdentifier resource identifier
153      * @param cmHandle cm handle identifier
154      * @param requestBody the request body
155      * @param contentType content type of body
156      * @return {@code ResponseEntity} response from dmi plugin
157      */
158     @Override
159     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String resourceIdentifier,
160         final String cmHandle, final Object requestBody, final String contentType) {
161         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
162                 resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
163         return new ResponseEntity<>(HttpStatus.CREATED);
164     }
165
166     /**
167      * Update resource data in datastore pass-through running for given cm-handle.
168      *
169      * @param resourceIdentifier resource identifier
170      * @param cmHandle cm handle identifier
171      * @param requestBody the request body
172      * @param contentType content type of the body
173      * @return response entity
174      */
175     @Override
176     public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String resourceIdentifier,
177                                                                        final String cmHandle,
178                                                                        final Object requestBody,
179                                                                        final String contentType) {
180         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
181                 resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
182         return new ResponseEntity<>(HttpStatus.OK);
183     }
184
185
186     /**
187      *  Delete resource data in datastore pass-through running for a given cm-handle.
188      *
189      * @param resourceIdentifier resource identifier
190      * @param cmHandle cm handle identifier
191      * @param contentType content type of the body
192      * @return response entity no content if request is successful
193      */
194     @Override
195     public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String cmHandle,
196                                                                      final String resourceIdentifier,
197                                                                      final String contentType) {
198         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
199             resourceIdentifier, DELETE, NO_BODY, contentType);
200         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
201     }
202
203     /**
204      * Execute cm handle search.
205      *
206      * @param conditions the conditions
207      * @return cm handles returned from search.
208      */
209     @Override
210     public ResponseEntity<CmHandles> executeCmHandleSearch(final Conditions conditions) {
211         final List<ConditionProperties> conditionProperties =
212             conditions.getConditions().stream().collect(Collectors.toList());
213         final CmHandles cmHandles = new CmHandles();
214         cmHandles.setCmHandles(toCmHandleProperties(processConditions(conditionProperties)));
215         return ResponseEntity.ok(cmHandles);
216     }
217
218     /**
219      * Query and return cm handles that match the given query parameters.
220      *
221      * @param cmHandleQueryRestParameters the cm handle query parameters
222      * @return collection of cm handle ids
223      */
224     public ResponseEntity<List<String>> queryCmHandles(
225         final CmHandleQueryRestParameters cmHandleQueryRestParameters) {
226         final Set<String> cmHandleIds = networkCmProxyDataService.queryCmHandles(
227             jsonObjectMapper.convertToValueType(cmHandleQueryRestParameters, CmHandleQueryApiParameters.class));
228         return ResponseEntity.ok(List.copyOf(cmHandleIds));
229     }
230
231     /**
232      * Search for Cm Handle and Properties by Name.
233      * @param cmHandleId cm-handle identifier
234      * @return cm handle and its properties
235      */
236     @Override
237     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
238         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
239         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
240         return ResponseEntity.ok(restOutputCmHandle);
241     }
242
243     /**
244      * Return module references for a cm handle.
245      *
246      * @param cmHandle the cm handle
247      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
248      */
249     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
250         final List<RestModuleReference> restModuleReferences =
251             networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
252             .map(ncmpRestInputMapper::toRestModuleReference)
253                 .collect(Collectors.toList());
254         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
255     }
256
257     private Collection<String> processConditions(final List<ConditionProperties> conditionProperties) {
258         for (final ConditionProperties conditionProperty : conditionProperties) {
259             if (conditionProperty.getName().equals("hasAllModules")) {
260                 return executeCmHandleSearchesForModuleNames(conditionProperty);
261             } else {
262                 log.warn("Unrecognized condition name {}.", conditionProperty.getName());
263             }
264         }
265         log.warn("No valid conditions found {}.", conditionProperties);
266         return Collections.emptyList();
267     }
268
269     private Collection<String> executeCmHandleSearchesForModuleNames(final ConditionProperties conditionProperties) {
270         return networkCmProxyDataService
271             .executeCmHandleHasAllModulesSearch(getModuleNames(conditionProperties.getConditionParameters()));
272     }
273
274     private Collection<String> getModuleNames(final ModuleNamesAsJsonArray moduleNamesAsJsonArray) {
275         final Collection<String> moduleNames = new ArrayList<>(moduleNamesAsJsonArray.size());
276         for (final ModuleNameAsJsonObject moduleNameAsJsonObject : moduleNamesAsJsonArray) {
277             moduleNames.add(moduleNameAsJsonObject.getModuleName());
278         }
279         return moduleNames;
280     }
281
282     private CmHandleProperties toCmHandleProperties(final Collection<String> cmHandleIdentifiers) {
283         final CmHandleProperties cmHandleProperties = new CmHandleProperties();
284         for (final String cmHandleIdentifier : cmHandleIdentifiers) {
285             final CmHandleProperty cmHandleProperty = new CmHandleProperty();
286             cmHandleProperty.setCmHandleId(cmHandleIdentifier);
287             cmHandleProperties.add(cmHandleProperty);
288         }
289         return cmHandleProperties;
290     }
291
292     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
293         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
294         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
295         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
296         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
297         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
298         return restOutputCmHandle;
299     }
300
301     private ResponseEntity<Map<String, Object>> populateAsyncResponse(final String topicParamInQuery) {
302         final boolean processAsynchronously = hasTopicParameter(topicParamInQuery);
303         final Map<String, Object> responseData;
304         if (processAsynchronously) {
305             responseData = getAsyncResponseData();
306         } else {
307             responseData = null;
308         }
309         return ResponseEntity.ok().body(responseData);
310     }
311
312     private static boolean hasTopicParameter(final String topicName) {
313         if (topicName == null) {
314             return false;
315         }
316         if (CpsValidator.validateTopicName(topicName)) {
317             return true;
318         }
319         throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
320     }
321
322     private Map<String, Object> getAsyncResponseData() {
323         final Map<String, Object> asyncResponseData = new HashMap<>(1);
324         final String resourceDataRequestId = UUID.randomUUID().toString();
325         asyncResponseData.put(ASYNC_REQUEST_ID, resourceDataRequestId);
326         return asyncResponseData;
327     }
328
329 }