Refactoring persistence classes
[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-2023 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.DatastoreType.OPERATIONAL;
27 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_RUNNING;
28 import static org.onap.cps.ncmp.api.impl.operations.OperationType.CREATE;
29 import static org.onap.cps.ncmp.api.impl.operations.OperationType.DELETE;
30 import static org.onap.cps.ncmp.api.impl.operations.OperationType.PATCH;
31 import static org.onap.cps.ncmp.api.impl.operations.OperationType.UPDATE;
32
33 import java.util.Collection;
34 import java.util.List;
35 import java.util.stream.Collectors;
36 import lombok.RequiredArgsConstructor;
37 import lombok.extern.slf4j.Slf4j;
38 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
39 import org.onap.cps.ncmp.api.impl.exception.InvalidDatastoreException;
40 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
41 import org.onap.cps.ncmp.api.impl.operations.DatastoreType;
42 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
43 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
44 import org.onap.cps.ncmp.rest.api.NetworkCmProxyApi;
45 import org.onap.cps.ncmp.rest.controller.handlers.NcmpCachedResourceRequestHandler;
46 import org.onap.cps.ncmp.rest.controller.handlers.NcmpDatastoreRequestHandler;
47 import org.onap.cps.ncmp.rest.controller.handlers.NcmpPassthroughResourceRequestHandler;
48 import org.onap.cps.ncmp.rest.mapper.CmHandleStateMapper;
49 import org.onap.cps.ncmp.rest.mapper.DataOperationRequestMapper;
50 import org.onap.cps.ncmp.rest.model.CmHandlePublicProperties;
51 import org.onap.cps.ncmp.rest.model.CmHandleQueryParameters;
52 import org.onap.cps.ncmp.rest.model.DataOperationRequest;
53 import org.onap.cps.ncmp.rest.model.RestModuleDefinition;
54 import org.onap.cps.ncmp.rest.model.RestModuleReference;
55 import org.onap.cps.ncmp.rest.model.RestOutputCmHandle;
56 import org.onap.cps.ncmp.rest.model.RestOutputCmHandleCompositeState;
57 import org.onap.cps.ncmp.rest.model.RestOutputCmHandlePublicProperties;
58 import org.onap.cps.ncmp.rest.util.DeprecationHelper;
59 import org.onap.cps.utils.JsonObjectMapper;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.bind.annotation.RestController;
64
65 @Slf4j
66 @RestController
67 @RequestMapping("${rest.api.ncmp-base-path}")
68 @RequiredArgsConstructor
69 public class NetworkCmProxyController implements NetworkCmProxyApi {
70
71     private static final String NO_BODY = null;
72     private final NetworkCmProxyDataService networkCmProxyDataService;
73     private final JsonObjectMapper jsonObjectMapper;
74     private final DeprecationHelper deprecationHelper;
75     private final NcmpRestInputMapper ncmpRestInputMapper;
76     private final CmHandleStateMapper cmHandleStateMapper;
77     private final NcmpCachedResourceRequestHandler ncmpCachedResourceRequestHandler;
78     private final NcmpPassthroughResourceRequestHandler ncmpPassthroughResourceRequestHandler;
79     private final DataOperationRequestMapper dataOperationRequestMapper;
80
81     /**
82      * Get resource data from datastore.
83      *
84      * @param datastoreName        name of the datastore
85      * @param cmHandle             cm handle identifier
86      * @param resourceIdentifier   resource identifier
87      * @param optionsParamInQuery  options query parameter
88      * @param topicParamInQuery    topic query parameter
89      * @param includeDescendants   whether to include descendants or not
90      * @return {@code ResponseEntity} response from dmi plugin
91      */
92
93     @Override
94     public ResponseEntity<Object> getResourceDataForCmHandle(final String datastoreName,
95                                                              final String cmHandle,
96                                                              final String resourceIdentifier,
97                                                              final String optionsParamInQuery,
98                                                              final String topicParamInQuery,
99                                                              final Boolean includeDescendants) {
100
101
102         final NcmpDatastoreRequestHandler ncmpDatastoreRequestHandler = getNcmpDatastoreRequestHandler(datastoreName);
103         return ncmpDatastoreRequestHandler.executeRequest(datastoreName, cmHandle, resourceIdentifier,
104                 optionsParamInQuery, topicParamInQuery, includeDescendants);
105     }
106
107     @Override
108     public ResponseEntity<Object> executeDataOperationForCmHandles(final String topicParamInQuery,
109                                                                   final DataOperationRequest
110                                                                           dataOperationRequest) {
111         return ncmpPassthroughResourceRequestHandler.executeRequest(topicParamInQuery,
112                 dataOperationRequestMapper.toDataOperationRequest(dataOperationRequest));
113     }
114
115     /**
116      * Query resource data from datastore.
117      *
118      * @param datastoreName        name of the datastore
119      * @param cmHandle             cm handle identifier
120      * @param cpsPath              CPS Path
121      * @param optionsParamInQuery  options query parameter
122      * @param topicParamInQuery    topic query parameter
123      * @param includeDescendants   whether to include descendants or not
124      * @return {@code ResponseEntity} response from dmi plugin
125      */
126
127     @Override
128     public ResponseEntity<Object> queryResourceDataForCmHandle(final String datastoreName,
129                                                                final String cmHandle,
130                                                                final String cpsPath,
131                                                                final String optionsParamInQuery,
132                                                                final String topicParamInQuery,
133                                                                final Boolean includeDescendants) {
134         validateDataStore(OPERATIONAL, datastoreName);
135         return ncmpCachedResourceRequestHandler.executeRequest(cmHandle, cpsPath, includeDescendants);
136     }
137
138     /**
139      * Patch resource data from passthrough-running.
140      *
141      * @param datastoreName      name of the datastore
142      * @param cmHandle           cm handle identifier
143      * @param resourceIdentifier resource identifier
144      * @param requestBody        the request body
145      * @param contentType        content type of body
146      * @return {@code ResponseEntity} response from dmi plugin
147      */
148
149     @Override
150     public ResponseEntity<Object> patchResourceDataRunningForCmHandle(final String datastoreName,
151                                                                       final String cmHandle,
152                                                                       final String resourceIdentifier,
153                                                                       final Object requestBody,
154                                                                       final String contentType) {
155
156         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
157
158         final Object responseObject = networkCmProxyDataService
159                 .writeResourceDataPassThroughRunningForCmHandle(
160                         cmHandle, resourceIdentifier, PATCH,
161                         jsonObjectMapper.asJsonString(requestBody), contentType);
162         return ResponseEntity.ok(responseObject);
163     }
164
165     /**
166      * Create resource data in datastore pass-through running for given cm-handle.
167      *
168      * @param datastoreName      name of the datastore
169      * @param cmHandle           cm handle identifier
170      * @param resourceIdentifier resource identifier
171      * @param requestBody        the request body
172      * @param contentType        content type of body
173      * @return {@code ResponseEntity} response from dmi plugin
174      */
175     @Override
176     public ResponseEntity<Void> createResourceDataRunningForCmHandle(final String datastoreName,
177                                                                      final String cmHandle,
178                                                                      final String resourceIdentifier,
179                                                                      final Object requestBody,
180                                                                      final String contentType) {
181
182         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
183
184         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
185                 resourceIdentifier, CREATE, jsonObjectMapper.asJsonString(requestBody), contentType);
186         return new ResponseEntity<>(HttpStatus.CREATED);
187     }
188
189     /**
190      * Update resource data in datastore pass-through running for given cm-handle.
191      *
192      * @param datastoreName      name of the datastore
193      * @param cmHandle           cm handle identifier
194      * @param resourceIdentifier resource identifier
195      * @param requestBody        the request body
196      * @param contentType        content type of the body
197      * @return response entity
198      */
199
200     @Override
201     public ResponseEntity<Object> updateResourceDataRunningForCmHandle(final String datastoreName,
202                                                                        final String cmHandle,
203                                                                        final String resourceIdentifier,
204                                                                        final Object requestBody,
205                                                                        final String contentType) {
206         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
207
208         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
209                 resourceIdentifier, UPDATE, jsonObjectMapper.asJsonString(requestBody), contentType);
210         return new ResponseEntity<>(HttpStatus.OK);
211     }
212
213     /**
214      * Delete resource data in datastore pass-through running for a given cm-handle.
215      *
216      * @param datastoreName      name of the datastore
217      * @param cmHandle           cm handle identifier
218      * @param resourceIdentifier resource identifier
219      * @param contentType        content type of the body
220      * @return response entity no content if request is successful
221      */
222     @Override
223     public ResponseEntity<Void> deleteResourceDataRunningForCmHandle(final String datastoreName,
224                                                                      final String cmHandle,
225                                                                      final String resourceIdentifier,
226                                                                      final String contentType) {
227
228         validateDataStore(PASSTHROUGH_RUNNING, datastoreName);
229
230         networkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle(cmHandle,
231                 resourceIdentifier, DELETE, NO_BODY, contentType);
232         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
233     }
234
235     /**
236      * Query and return cm handles that match the given query parameters.
237      *
238      * @param cmHandleQueryParameters the cm handle query parameters
239      * @return collection of cm handles
240      */
241     @Override
242     @SuppressWarnings("deprecation") // mapOldConditionProperties method will be removed in Release 12
243     public ResponseEntity<List<RestOutputCmHandle>> searchCmHandles(
244             final CmHandleQueryParameters cmHandleQueryParameters) {
245         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
246                 deprecationHelper.mapOldConditionProperties(cmHandleQueryParameters);
247         final Collection<NcmpServiceCmHandle> cmHandles = networkCmProxyDataService
248                 .executeCmHandleSearch(cmHandleQueryApiParameters);
249         final List<RestOutputCmHandle> outputCmHandles =
250                 cmHandles.stream().map(this::toRestOutputCmHandle).collect(Collectors.toList());
251         return ResponseEntity.ok(outputCmHandles);
252     }
253
254     /**
255      * Query and return cm handle ids that match the given query parameters.
256      *
257      * @param cmHandleQueryParameters the cm handle query parameters
258      * @return collection of cm handle ids
259      */
260     @Override
261     public ResponseEntity<List<String>> searchCmHandleIds(
262             final CmHandleQueryParameters cmHandleQueryParameters) {
263         final CmHandleQueryApiParameters cmHandleQueryApiParameters =
264                 jsonObjectMapper.convertToValueType(cmHandleQueryParameters, CmHandleQueryApiParameters.class);
265         final Collection<String> cmHandleIds
266             = networkCmProxyDataService.executeCmHandleIdSearch(cmHandleQueryApiParameters);
267         return ResponseEntity.ok(List.copyOf(cmHandleIds));
268     }
269
270     /**
271      * Search for Cm Handle and Properties by Name.
272      *
273      * @param cmHandleId cm-handle identifier
274      * @return cm handle and its properties
275      */
276     @Override
277     public ResponseEntity<RestOutputCmHandle> retrieveCmHandleDetailsById(final String cmHandleId) {
278         final NcmpServiceCmHandle ncmpServiceCmHandle = networkCmProxyDataService.getNcmpServiceCmHandle(cmHandleId);
279         final RestOutputCmHandle restOutputCmHandle = toRestOutputCmHandle(ncmpServiceCmHandle);
280         return ResponseEntity.ok(restOutputCmHandle);
281     }
282
283     /**
284      * Get Cm Handle Properties by Cm Handle Id.
285      *
286      * @param cmHandleId cm-handle identifier
287      * @return cm handle properties
288      */
289     @Override
290     public ResponseEntity<RestOutputCmHandlePublicProperties> getCmHandlePublicPropertiesByCmHandleId(
291             final String cmHandleId) {
292         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
293         cmHandlePublicProperties.add(networkCmProxyDataService.getCmHandlePublicProperties(cmHandleId));
294         final RestOutputCmHandlePublicProperties restOutputCmHandlePublicProperties =
295                 new RestOutputCmHandlePublicProperties();
296         restOutputCmHandlePublicProperties.setPublicCmHandleProperties(cmHandlePublicProperties);
297         return ResponseEntity.ok(restOutputCmHandlePublicProperties);
298     }
299
300     /**
301      * Get Cm Handle State by Cm Handle Id.
302      *
303      * @param cmHandleId cm-handle identifier
304      * @return cm handle state
305      */
306     @Override
307     public ResponseEntity<RestOutputCmHandleCompositeState> getCmHandleStateByCmHandleId(
308             final String cmHandleId) {
309         final CompositeState cmHandleState = networkCmProxyDataService.getCmHandleCompositeState(cmHandleId);
310         final RestOutputCmHandleCompositeState restOutputCmHandleCompositeState =
311                 new RestOutputCmHandleCompositeState();
312         restOutputCmHandleCompositeState.setState(
313                 cmHandleStateMapper.toCmHandleCompositeStateExternalLockReason(cmHandleState));
314         return ResponseEntity.ok(restOutputCmHandleCompositeState);
315     }
316
317     /**
318      * Return module definitions for a cm handle.
319      *
320      * @param cmHandleId cm-handle identifier
321      * @return list of module definitions (module name, revision, yang resource content)
322      */
323     @Override
324     public ResponseEntity<List<RestModuleDefinition>> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
325         final List<RestModuleDefinition> restModuleDefinitions =
326                 networkCmProxyDataService.getModuleDefinitionsByCmHandleId(cmHandleId).stream()
327                         .map(ncmpRestInputMapper::toRestModuleDefinition)
328                         .collect(Collectors.toList());
329         return new ResponseEntity<>(restModuleDefinitions, HttpStatus.OK);
330     }
331
332     /**
333      * Return module references for a cm handle.
334      *
335      * @param cmHandle the cm handle
336      * @return module references for cm handle. Namespace will be always blank because restConf does not include this.
337      */
338     public ResponseEntity<List<RestModuleReference>> getModuleReferencesByCmHandle(final String cmHandle) {
339         final List<RestModuleReference> restModuleReferences =
340                 networkCmProxyDataService.getYangResourcesModuleReferences(cmHandle).stream()
341                         .map(ncmpRestInputMapper::toRestModuleReference)
342                         .collect(Collectors.toList());
343         return new ResponseEntity<>(restModuleReferences, HttpStatus.OK);
344     }
345
346     /**
347      * Set the data sync enabled flag, along with the data sync state for the specified cm handle.
348      *
349      * @param cmHandleId          cm handle id
350      * @param dataSyncEnabledFlag data sync enabled flag
351      * @return response entity ok if request is successful
352      */
353     @Override
354     public ResponseEntity<Object> setDataSyncEnabledFlagForCmHandle(final String cmHandleId,
355                                                                     final Boolean dataSyncEnabledFlag) {
356         networkCmProxyDataService.setDataSyncEnabled(cmHandleId, dataSyncEnabledFlag);
357         return new ResponseEntity<>(HttpStatus.OK);
358     }
359
360
361     private RestOutputCmHandle toRestOutputCmHandle(final NcmpServiceCmHandle ncmpServiceCmHandle) {
362         final RestOutputCmHandle restOutputCmHandle = new RestOutputCmHandle();
363         final CmHandlePublicProperties cmHandlePublicProperties = new CmHandlePublicProperties();
364         restOutputCmHandle.setCmHandle(ncmpServiceCmHandle.getCmHandleId());
365         cmHandlePublicProperties.add(ncmpServiceCmHandle.getPublicProperties());
366         restOutputCmHandle.setPublicCmHandleProperties(cmHandlePublicProperties);
367         restOutputCmHandle.setState(cmHandleStateMapper.toCmHandleCompositeStateExternalLockReason(
368                 ncmpServiceCmHandle.getCompositeState()));
369         return restOutputCmHandle;
370     }
371
372     private void validateDataStore(final DatastoreType acceptableDataStoreType, final String requestedDatastoreName) {
373         final DatastoreType datastoreType = DatastoreType.fromDatastoreName(requestedDatastoreName);
374
375         if (acceptableDataStoreType != datastoreType) {
376             throw new InvalidDatastoreException(requestedDatastoreName + " is not supported");
377         }
378     }
379
380     private NcmpDatastoreRequestHandler getNcmpDatastoreRequestHandler(final String datastoreName) {
381         if (OPERATIONAL.equals(DatastoreType.fromDatastoreName(datastoreName))) {
382             return ncmpCachedResourceRequestHandler;
383         }
384         return ncmpPassthroughResourceRequestHandler;
385     }
386
387
388 }
389