Merge "Changed the object mapper to ignore unknown fields"
[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 static org.apache.commons.lang3.StringUtils.isBlank
24 import javax.ws.rs.NotFoundException
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.aai.domain.yang.ServiceProfile
28 import org.onap.aai.domain.yang.ServiceProfiles
29 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
30 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri
31 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
32 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
34 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
35 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
36 import org.onap.so.bpmn.common.scripts.ExceptionUtil
37 import org.onap.so.bpmn.common.scripts.MsoUtils
38 import org.onap.so.bpmn.common.scripts.RequestDBUtil
39 import org.onap.so.bpmn.core.WorkflowException
40 import org.onap.so.bpmn.core.json.JsonUtils
41 import org.onap.so.db.request.beans.OperationStatus
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
44
45 class DeleteSliceService extends AbstractServiceTaskProcessor {
46
47     private final String PREFIX ="DeleteSliceService"
48     ExceptionUtil exceptionUtil = new ExceptionUtil()
49     JsonUtils jsonUtil = new JsonUtils()
50     private RequestDBUtil requestDBUtil = new RequestDBUtil()
51
52     private static final Logger LOGGER = LoggerFactory.getLogger( DeleteSliceService.class)
53
54     @Override
55     void preProcessRequest(DelegateExecution execution) {
56         execution.setVariable("prefix", PREFIX)
57         String msg = ""
58
59         LOGGER.debug("*****${PREFIX} preProcessRequest *****")
60
61         try {
62             // check for incoming json message/input
63             String siRequest = execution.getVariable("bpmnRequest")
64             String requestId = execution.getVariable("mso-request-id")
65             execution.setVariable("msoRequestId", requestId)
66
67             //e2eslice-service instance id
68             String serviceInstanceId = execution.getVariable("serviceInstanceId")
69             if (isBlank(serviceInstanceId)) {
70                 msg = "e2eslice-service id is null"
71                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
72             }
73             LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
74
75             //subscriberInfo
76             checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
77             checkAndSetRequestParam(siRequest,"serviceType",false, execution)
78             checkAndSetRequestParam(siRequest,"operationId",false, execution)
79             checkAndSetRequestParam(siRequest,"scriptName",false, execution)
80             //prepare init operation status
81             execution.setVariable("progress", "0")
82             execution.setVariable("result", "processing")
83             execution.setVariable("operationType", "DELETE")
84             execution.setVariable("operationContent", "Delete Slice service operation start")
85             updateServiceOperationStatus(execution)
86
87         } catch (BpmnError e) {
88             throw e
89         } catch (Exception ex) {
90             msg = "Exception in preProcessRequest " + ex.getMessage()
91             LOGGER.debug(msg)
92             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
93         }
94         LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
95     }
96
97     /**
98      * send asynchronous response
99      * @param execution
100      */
101     void sendAsyncResponse(DelegateExecution execution) {
102         LOGGER.trace("${PREFIX} Start sendSyncResponse ")
103
104         try {
105             String operationId = execution.getVariable("operationId")
106             String syncResponse = """{"operationId":"${operationId}"}""".trim()
107             LOGGER.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
108             sendWorkflowResponse(execution, 202, syncResponse)
109
110         } catch (Exception ex) {
111             String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
112             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
113         }
114         LOGGER.trace("${PREFIX} Exit sendSyncResponse")
115     }
116
117     /**
118      * Deletes the slice service instance in aai
119      */
120     void deleteSliceServiceInstance(DelegateExecution execution) {
121         LOGGER.trace("${PREFIX} Start deleteSliceServiceInstance")
122         try {
123
124             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(execution.getVariable("serviceInstanceId")))
125             getAAIClient().delete(serviceInstanceUri)
126
127             execution.setVariable("progress", "100")
128             execution.setVariable("result", "finished")
129             execution.setVariable("operationContent", "NSMF completes slicing service termination.")
130             updateServiceOperationStatus(execution)
131
132             LOGGER.trace("${PREFIX} Exited deleteSliceServiceInstance")
133         }catch(Exception e){
134             LOGGER.debug("Error occured within deleteSliceServiceInstance method: " + e)
135             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
136         }
137     }
138
139     /**
140      * update operation status
141      * @param execution
142      */
143     private void updateServiceOperationStatus(DelegateExecution execution){
144
145         OperationStatus operationStatus = new OperationStatus()
146         operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
147         operationStatus.setOperationId(execution.getVariable("operationId"))
148         operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
149         operationStatus.setResult(execution.getVariable("result"))
150         operationStatus.setProgress(execution.getVariable("progress"))
151         operationStatus.setOperationContent(execution.getVariable("operationContent"))
152         operationStatus.setReason(execution.getVariable("reason"))
153         operationStatus.setOperation(execution.getVariable("operationType"))
154
155         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
156     }
157
158     /**
159      * delete service profile from aai
160      * @param execution
161      */
162     void delServiceProfileFromAAI(DelegateExecution execution)
163     {
164         String globalSubscriberId = execution.getVariable("globalSubscriberId")
165         String serviceType = execution.getVariable("serviceType")
166         String serviceInstanceId = execution.getVariable("serviceInstanceId")
167         String profileId = ""
168
169         try
170         {
171             AAIPluralResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceInstanceId).serviceProfiles())
172             AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
173             Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
174             if(serviceProfilesOpt.isPresent()){
175                 ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
176                 ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
177                 profileId = serviceProfile ? serviceProfile.getProfileId() : ""
178             }
179             resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceInstanceId).serviceProfile(profileId))
180             if (!getAAIClient().exists(resourceUri)) {
181                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
182             }
183             getAAIClient().delete(resourceUri)
184         }
185         catch (any)
186         {
187             String msg = "delete service profile from aai failed! cause-"+any.getCause()
188             LOGGER.error(any.printStackTrace())
189             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
190         }
191     }
192
193      void sendSyncError(DelegateExecution execution) {
194         LOGGER.debug("${PREFIX} Start sendSyncError")
195
196         try {
197             String errorMessage = "Sending Sync Error."
198             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
199                 WorkflowException wfe = execution.getVariable("WorkflowException")
200                 errorMessage = wfe.getErrorMessage()
201             }
202
203             String buildworkflowException =
204                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
205                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
206                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
207                                    </aetgt:WorkflowException>"""
208
209             LOGGER.debug(buildworkflowException)
210             sendWorkflowResponse(execution, 500, buildworkflowException)
211
212         } catch (Exception ex) {
213             LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
214         }
215
216     }
217
218     void prepareEndOperationStatus(DelegateExecution execution){
219         LOGGER.debug(" ======== ${PREFIX} STARTED prepareEndOperationStatus Process ======== ")
220
221         execution.setVariable("progress", "100")
222         execution.setVariable("result", "error")
223         execution.setVariable("operationContent", "NSSMF Terminate service failure")
224
225         WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
226         String errorMessage = wfex.getErrorMessage()
227         errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
228         execution.setVariable("reason",errorMessage)
229         updateServiceOperationStatus(execution)
230
231         LOGGER.debug("======== ${PREFIX} COMPLETED prepareEndOperationStatus Process ======== ")
232     }
233
234     /**
235      * check parameters from request body
236      * set to execution
237      * @param siRequest
238      * @param paraName
239      * @param isErrorException
240      * @param execution
241      */
242     private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
243     {
244         String msg = ""
245         String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
246         if (isBlank(paramValue)) {
247             msg = "Input ${paraName} is null"
248             LOGGER.error(msg)
249             if(isErrorException)
250             {
251                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
252             }
253
254         } else {
255             execution.setVariable(paraName, paramValue)
256         }
257     }
258 }