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