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