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