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