Merge "create custom spring aop annotation for logging"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DeleteSliceService.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (c) 2019, CMCC Technologies Co., Ltd.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.ServiceProfile
26 import org.onap.aai.domain.yang.ServiceProfiles
27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.MsoUtils
30 import org.onap.so.bpmn.common.scripts.RequestDBUtil
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.json.JsonUtils
33 import org.onap.so.client.aai.AAIObjectType
34 import org.onap.so.client.aai.AAIResourcesClient
35 import org.onap.so.client.aai.entities.AAIResultWrapper
36 import org.onap.so.client.aai.entities.uri.AAIResourceUri
37 import org.onap.so.client.aai.entities.uri.AAIUriFactory
38 import org.onap.so.db.request.beans.OperationStatus
39 import org.slf4j.Logger
40 import org.slf4j.LoggerFactory
41
42 import javax.ws.rs.NotFoundException
43
44 import static org.apache.commons.lang3.StringUtils.isBlank
45
46 class DeleteSliceService extends AbstractServiceTaskProcessor {
47
48     private final String PREFIX ="DeleteSliceService"
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50     JsonUtils jsonUtil = new JsonUtils()
51     private RequestDBUtil requestDBUtil = new RequestDBUtil()
52
53     private static final Logger LOGGER = LoggerFactory.getLogger( DeleteSliceService.class)
54
55     @Override
56     void preProcessRequest(DelegateExecution execution) {
57         execution.setVariable("prefix", PREFIX)
58         String msg = ""
59
60         LOGGER.debug("*****${PREFIX} preProcessRequest *****")
61
62         try {
63             // check for incoming json message/input
64             String siRequest = execution.getVariable("bpmnRequest")
65             String requestId = execution.getVariable("mso-request-id")
66             execution.setVariable("msoRequestId", requestId)
67
68             //e2eslice-service instance id
69             String serviceInstanceId = execution.getVariable("serviceInstanceId")
70             if (isBlank(serviceInstanceId)) {
71                 msg = "e2eslice-service id is null"
72                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
73             }
74             LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
75
76             //subscriberInfo
77             checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
78             checkAndSetRequestParam(siRequest,"serviceType",false, execution)
79             checkAndSetRequestParam(siRequest,"operationId",false, execution)
80
81             //prepare init operation status
82             execution.setVariable("progress", "0")
83             execution.setVariable("result", "processing")
84             execution.setVariable("operationType", "DELETE")
85             execution.setVariable("operationContent", "Delete Slice service operation start")
86             updateServiceOperationStatus(execution)
87
88         } catch (BpmnError e) {
89             throw e
90         } catch (Exception ex) {
91             msg = "Exception in preProcessRequest " + ex.getMessage()
92             LOGGER.debug(msg)
93             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
94         }
95         LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
96     }
97
98     /**
99      * send asynchronous response
100      * @param execution
101      */
102     void sendAsyncResponse(DelegateExecution execution) {
103         LOGGER.trace("${PREFIX} Start sendSyncResponse ")
104
105         try {
106             String operationId = execution.getVariable("operationId")
107             String syncResponse = """{"operationId":"${operationId}"}""".trim()
108             LOGGER.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
109             sendWorkflowResponse(execution, 202, syncResponse)
110
111         } catch (Exception ex) {
112             String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
113             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
114         }
115         LOGGER.trace("${PREFIX} Exit sendSyncResponse")
116     }
117
118     /**
119      * Deletes the slice service instance in aai
120      */
121     void deleteSliceServiceInstance(DelegateExecution execution) {
122         LOGGER.trace("${PREFIX} Start deleteSliceServiceInstance")
123         try {
124
125             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
126             getAAIClient().delete(serviceInstanceUri)
127
128             execution.setVariable("progress", "100")
129             execution.setVariable("result", "finished")
130             execution.setVariable("operationContent", "NSMF completes slicing service termination.")
131             updateServiceOperationStatus(execution)
132
133             LOGGER.trace("${PREFIX} Exited deleteSliceServiceInstance")
134         }catch(Exception e){
135             LOGGER.debug("Error occured within deleteSliceServiceInstance method: " + e)
136             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
137         }
138     }
139
140     /**
141      * update operation status
142      * @param execution
143      */
144     private void updateServiceOperationStatus(DelegateExecution execution){
145
146         OperationStatus operationStatus = new OperationStatus()
147         operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
148         operationStatus.setOperationId(execution.getVariable("operationId"))
149         operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
150         operationStatus.setResult(execution.getVariable("result"))
151         operationStatus.setProgress(execution.getVariable("progress"))
152         operationStatus.setOperationContent(execution.getVariable("operationContent"))
153         operationStatus.setReason(execution.getVariable("reason"))
154         operationStatus.setOperation(execution.getVariable("operationType"))
155
156         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
157     }
158
159     /**
160      * delete service profile from aai
161      * @param execution
162      */
163     void delServiceProfileFromAAI(DelegateExecution execution)
164     {
165         String globalSubscriberId = execution.getVariable("globalSubscriberId")
166         String serviceType = execution.getVariable("serviceType")
167         String serviceInstanceId = execution.getVariable("serviceInstanceId")
168         String profileId = ""
169
170         try
171         {
172             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
173             AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
174             Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
175             if(serviceProfilesOpt.isPresent()){
176                 ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
177                 ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
178                 profileId = serviceProfile ? serviceProfile.getProfileId() : ""
179             }
180             resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
181             if (!getAAIClient().exists(resourceUri)) {
182                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
183             }
184             getAAIClient().delete(resourceUri)
185         }
186         catch (any)
187         {
188             String msg = "delete service profile from aai failed! cause-"+any.getCause()
189             LOGGER.error(any.printStackTrace())
190             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
191         }
192     }
193
194      void sendSyncError(DelegateExecution execution) {
195         LOGGER.debug("${PREFIX} Start sendSyncError")
196
197         try {
198             String errorMessage = "Sending Sync Error."
199             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
200                 WorkflowException wfe = execution.getVariable("WorkflowException")
201                 errorMessage = wfe.getErrorMessage()
202             }
203
204             String buildworkflowException =
205                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
206                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
207                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
208                                    </aetgt:WorkflowException>"""
209
210             LOGGER.debug(buildworkflowException)
211             sendWorkflowResponse(execution, 500, buildworkflowException)
212
213         } catch (Exception ex) {
214             LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
215         }
216
217     }
218
219     void prepareEndOperationStatus(DelegateExecution execution){
220         LOGGER.debug(" ======== ${PREFIX} STARTED prepareEndOperationStatus Process ======== ")
221
222         execution.setVariable("progress", "100")
223         execution.setVariable("result", "error")
224         execution.setVariable("operationContent", "NSSMF Terminate service failure")
225
226         WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
227         String errorMessage = wfex.getErrorMessage()
228         errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
229         execution.setVariable("reason",errorMessage)
230         updateServiceOperationStatus(execution)
231
232         LOGGER.debug("======== ${PREFIX} COMPLETED prepareEndOperationStatus Process ======== ")
233     }
234
235     /**
236      * check parameters from request body
237      * set to execution
238      * @param siRequest
239      * @param paraName
240      * @param isErrorException
241      * @param execution
242      */
243     private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
244     {
245         String msg = ""
246         String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
247         if (isBlank(paramValue)) {
248             msg = "Input ${paraName} is null"
249             LOGGER.error(msg)
250             if(isErrorException)
251             {
252                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
253             }
254
255         } else {
256             execution.setVariable(paraName, paramValue)
257         }
258     }
259 }