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