fb234ef71a1d1944d44d4a03d051dfb936e067a7
[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     @SuppressWarnings("deprecation") // mapOldConditionProperties method will be removed in Release 12
215     public ResponseEntity<List<RestOutputCmHandle>> searchCmHandles(
216             final CmHandleQueryParameters cmHandleQueryParameters) {
217         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
218                 deprecationHelper.mapOldConditionProperties(cmHandleQueryParameters);
219         final Set<NcmpServiceCmHandle> cmHandles = networkCmProxyDataService
220                 .executeCmHandleSearch(cmHandleQueryApiParameters);
221         final List<RestOutputCmHandle> outputCmHandles =
222                 cmHandles.stream().map(this::toRestOutputCmHandle).collect(Collectors.toList());
223         return ResponseEntity.ok(outputCmHandles);
224     }
225
226     /**
227      * Query and return cm handle ids that match the given query parameters.
228      *
229      * @param cmHandleQueryParameters the cm handle query parameters
230      * @return collection of cm handle ids
231      */
232     @Override
233     public ResponseEntity<List<String>> searchCmHandleIds(
234         final CmHandleQueryParameters cmHandleQueryParameters) {
235         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
236                 jsonObjectMapper.convertToValueType(cmHandleQueryParameters, CmHandleQueryApiParameters.class);
237         final Set<String> cmHandleIds = networkCmProxyDataService.executeCmHandleIdSearch(cmHandleQueryApiParameters);
238         return ResponseEntity.ok(List.copyOf(cmHandleIds));
239     }
240
241     /**
242      * Search for Cm Handle and Properties by Name.
243      * @param cmHandleId cm-handle identifier
244      * @return cm handle and its properties
245      */
246     @Override
247     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
248         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
249         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
250         return ResponseEntity.ok(restOutputCmHandle);
251     }
252
253     /**
254      * Get Cm Handle Properties by Cm Handle Id.
255      * @param cmHandleId cm-handle identifier
256      * @return cm handle and its properties
257      */
258     @Override
259     public ResponseEntity<RestOutputCmHandlePublicProperties> getCmHandlePublicPropertiesByCmHandleId(
260         final String cmHandleId) {
261         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
262         cmHandlePublicProperties.add(networkCmProxyDataService.getCmHandlePublicProperties(cmHandleId));
263         final RestOutputCmHandlePublicProperties restOutputCmHandlePublicProperties =
264             new RestOutputCmHandlePublicProperties();
265         restOutputCmHandlePublicProperties.setPublicCmHandleProperties(cmHandlePublicProperties);
266         return ResponseEntity.ok(restOutputCmHandlePublicProperties);
267     }
268
269     /**
270      * Return module references for a cm handle.
271      *
272      * @param cmHandle the cm handle
273      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
274      */
275     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
276         final List<RestModuleReference> restModuleReferences =
277             networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
278             .map(ncmpRestInputMapper::toRestModuleReference)
279                 .collect(Collectors.toList());
280         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
281     }
282
283     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
284         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
285         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
286         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
287         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
288         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
289         restOutputCmHandle.setState(restOutputCmHandleStateMapper.toRestOutputCmHandleState(
290                 ncmpServiceCmHandle.getCompositeState()));
291         return restOutputCmHandle;
292     }
293
294     private static boolean isValidTopic(final String topicName) {
295         if (topicName == null) {
296             return false;
297         }
298         if (CpsValidator.validateTopicName(topicName)) {
299             return true;
300         }
301         throw new InvalidTopicException("Topic name " + topicName + " is invalid", "invalid topic");
302     }
303
304     private ResponseEntity<Object> acknowledgeAsyncRequest(final String requestId) {
305         final Map<String, Object> acknowledgeData = new HashMap<>(1);
306         acknowledgeData.put("requestId", requestId);
307         return ResponseEntity.ok(acknowledgeData);
308     }
309
310 }
311