Merge "Add APPC-related Activities for WFD"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DeleteCustomE2EServiceInstance.groovy
1 /*-
2
3  * ============LICENSE_START=======================================================
4  * ONAP - SO
5  * ================================================================================
6  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
7  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. 
8  * ================================================================================
9  * Modifications Copyright (c) 2019 Samsung
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.so.bpmn.infrastructure.scripts;
26
27 import static org.apache.commons.lang3.StringUtils.*;
28
29 import org.apache.commons.lang3.*
30 import org.camunda.bpm.engine.delegate.BpmnError
31 import org.camunda.bpm.engine.delegate.DelegateExecution
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.common.scripts.VidUtils
36 import org.onap.so.bpmn.core.WorkflowException
37 import org.onap.so.bpmn.core.json.JsonUtils
38 import org.onap.so.bpmn.core.UrnPropertiesReader
39 import org.slf4j.Logger
40 import org.slf4j.LoggerFactory
41 import org.springframework.web.util.UriUtils;
42
43 import groovy.json.*
44
45 /**
46  * This groovy class supports the <class>DelE2EServiceInstance.bpmn</class> process.
47  *
48  */
49 public class DeleteCustomE2EServiceInstance extends AbstractServiceTaskProcessor {
50
51         String Prefix="DELSI_"
52         ExceptionUtil exceptionUtil = new ExceptionUtil()
53         JsonUtils jsonUtil = new JsonUtils()
54         VidUtils vidUtils = new VidUtils()
55     private static final Logger logger = LoggerFactory.getLogger( DeleteCustomE2EServiceInstance.class);
56         
57         public void preProcessRequest (DelegateExecution execution) {
58                 execution.setVariable("prefix",Prefix)
59                 String msg = ""
60                 
61                 logger.info("Starting preProcessRequest")
62
63                 try {
64                         // check for incoming json message/input
65                         String siRequest = execution.getVariable("bpmnRequest")
66                         logger.debug(siRequest)
67                         
68                         
69                         String requestId = execution.getVariable("mso-request-id")
70                         execution.setVariable("msoRequestId", requestId)
71                         logger.info("Input Request:" + siRequest + " reqId:" + requestId)
72                         
73                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
74                         if (isBlank(serviceInstanceId)) {
75                                 msg = "Input serviceInstanceId' is null"
76                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
77                         }
78                 
79                                 
80                         //requestInfo
81 //                      String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
82 //                      if (isBlank(productFamilyId))
83 //                      {
84 //                              msg = "Input productFamilyId is null"
85 //                              logger.info( msg)
86 //                              //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
87 //                      } else {
88 //                              execution.setVariable("productFamilyId", productFamilyId)
89 //                      }
90                         String source = jsonUtil.getJsonValue(siRequest, "source")
91                         execution.setVariable("source", source)
92                         
93                         //subscriberInfo
94                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId")
95                         if (isBlank(globalSubscriberId)) {
96                                 msg = "Input globalSubscriberId' is null"
97                                 logger.info(msg)
98                         } else {
99                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
100                         }
101                         
102                         //requestParameters
103                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType")
104                         if (isBlank(subscriptionServiceType)) {
105                                 msg = "Input subscriptionServiceType is null"
106                                 logger.debug(msg)
107                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
108                         } else {
109                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
110                         }
111                         String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
112                         execution.setVariable("operationId", operationId)
113                         
114                         execution.setVariable("operationType", "DELETE") 
115                 } catch (BpmnError e) {
116                         throw e
117                 } catch (Exception ex){
118                         msg = "Exception in preProcessRequest " + ex.getMessage()
119                         logger.info(msg)
120                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
121                 }
122                 logger.trace("Exit preProcessRequest")
123         }
124
125         public void sendSyncResponse (DelegateExecution execution) {
126                 logger.trace("Staring sendSyncResponse")
127
128                 try {
129                         String operationId = execution.getVariable("operationId")
130                         String syncResponse = """{"operationId":"${operationId}"}""".trim()
131                         logger.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
132                         sendWorkflowResponse(execution, 202, syncResponse)
133
134                 } catch (Exception ex) {
135                         String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
136                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
137                 }
138                 logger.trace("Exit sendSyncResopnse")
139         }
140         
141         public void sendSyncError (DelegateExecution execution) {
142                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
143                 logger.info("Starting sendSyncError")
144
145                 try {
146                         String errorMessage = ""
147                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
148                                 WorkflowException wfe = execution.getVariable("WorkflowException")
149                                 errorMessage = wfe.getErrorMessage()
150                         } else {
151                                 errorMessage = "Sending Sync Error."
152                         }
153
154                         String buildworkflowException =
155                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
156                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
157                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
158                                    </aetgt:WorkflowException>"""
159
160                         logger.info(buildworkflowException)
161                         sendWorkflowResponse(execution, 500, buildworkflowException)
162
163                 } catch (Exception ex) {
164                         logger.info("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
165                 }
166
167         }
168         
169         public void prepareCompletionRequest (DelegateExecution execution) {
170                 logger.trace("Starting prepareCompletion")
171
172                 try {
173                         String requestId = execution.getVariable("msoRequestId")
174                         String source = execution.getVariable("source")
175                         String msoCompletionRequest =
176                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
177                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
178                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
179                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
180                                                         <action>DELETE</action>
181                                                         <source>${MsoUtils.xmlEscape(source)}</source>
182                                                 </request-info>
183                                                 <aetgt:status-message>E2E Service Instance was deleted successfully.</aetgt:status-message>
184                                                 <aetgt:mso-bpel-name>DeleteCustomE2EServiceInstance</aetgt:mso-bpel-name>
185                                         </aetgt:MsoCompletionRequest>"""
186
187                         // Format Response
188                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
189
190                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
191                         logger.info(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
192
193                 } catch (Exception ex) {
194                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
195                         logger.info(msg)
196                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
197                 }
198                 logger.trace("Exit prepareCompletionRequest")
199         }
200         
201         public void prepareFalloutRequest(DelegateExecution execution){
202                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
203                 logger.trace("Starting prepareFalloutRequest ")
204
205                 try {
206                         WorkflowException wfex = execution.getVariable("WorkflowException")
207                         logger.info(" Input Workflow Exception: " + wfex.toString())
208                         String requestId = execution.getVariable("msoRequestId")
209                         String source = execution.getVariable("source")
210                         String requestInfo =
211                         """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
212                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
213                                         <action>DELETE</action>
214                                         <source>${MsoUtils.xmlEscape(source)}</source>
215                                    </request-info>"""
216
217                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
218                         execution.setVariable("falloutRequest", falloutRequest)
219                 } catch (Exception ex) {
220                         logger.info("Exception prepareFalloutRequest:" + ex.getMessage())
221                         String errorException = "  Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
222                         String requestId = execution.getVariable("msoRequestId")
223                         String falloutRequest =
224                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
225                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
226                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
227                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
228                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
229                                               <action>DELETE</action>
230                                               <source>VID</source>
231                                            </request-info>
232                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
233                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
234                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
235                                                 </aetgt:WorkflowException>
236                                         </aetgt:FalloutHandlerRequest>"""
237
238                         execution.setVariable("falloutRequest", falloutRequest)
239                 }
240                 logger.trace("Exit prepareFalloutRequest")
241         }
242         
243
244         // *******************************
245         //     Build DB request Section
246         // *******************************
247         public void prepareDBRequest (DelegateExecution execution) {
248                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
249                 execution.setVariable("prefix", Prefix)
250
251                 try {
252                         logger.info("Starting prepareDBRequest")
253
254                         String requestId = execution.getVariable("DELSI_requestId")
255                         String statusMessage = "E2E Service Instance successfully deleted."
256
257                         //TODO - verify the format for Service Instance Delete,
258                         String dbRequest =
259                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
260                                                 <soapenv:Header/>
261                                                 <soapenv:Body>
262                                                         <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb">
263                                                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
264                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
265                                                                 <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage>
266                                                                 <responseBody></responseBody>
267                                                                 <requestStatus>COMPLETED</requestStatus>
268                                                                 <progress>100</progress>
269                                                         </ns:updateInfraRequest>
270                                                    </soapenv:Body>
271                                            </soapenv:Envelope>"""
272
273                    String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
274                    execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString)
275                   logger.info(buildDeleteDBRequestAsString)
276
277                 } catch (Exception ex) {
278                         // try error in method block
279                         String exceptionMessage = "Bpmn error encountered in DeleteCustomE2EServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage()
280                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
281
282                 }
283
284          }
285
286         // *******************************
287         //     Build Error Section
288         // *******************************
289         public void prepareDBRequestError (DelegateExecution execution) {
290                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
291                 execution.setVariable("prefix", Prefix)
292
293                 logger.trace("Start prepareDBRequestError")
294
295                 try {
296                         String requestId = execution.getVariable("DELSI_requestId")
297                         String statusMessage = ""
298                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
299                                 WorkflowException wfe = execution.getVariable("WorkflowException")
300                                 statusMessage = wfe.getErrorMessage()
301
302                         } else {
303                                 statusMessage = "Encountered Error during DeleteCustomE2EServiceInstance proccessing. "
304                         }
305
306                         //TODO - verify the format for Service Instance Create,
307                         String dbRequest =
308                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
309                                                 <soapenv:Header/>
310                                                 <soapenv:Body>
311                                                         <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb">
312                                                                 <requestId>${MsoUtils.xmlEscape(requestId)}</requestId>
313                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
314                                                                 <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage>
315                                                                 <responseBody></responseBody>
316                                                                 <requestStatus>FAILED</requestStatus>
317                                                         </ns:updateInfraRequest>
318                                                    </soapenv:Body>
319                                            </soapenv:Envelope>"""
320
321                    String buildDBRequestAsString = utils.formatXml(dbRequest)
322                    execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString)
323                    logger.info(buildDBRequestAsString)
324
325                 } catch (Exception ex) {
326                         // try error in method block
327                         String exceptionMessage = "Bpmn error encountered in DeleteCustomE2EServiceInstance flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage()
328                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
329
330                 }
331
332          }
333
334         public void processJavaException(DelegateExecution execution) {
335                 //TODO:
336         }
337
338         /**
339          * Init the service Operation Status
340          */
341         public void prepareInitServiceOperationStatus(DelegateExecution execution){
342                 logger.debug("======== STARTED prepareInitServiceOperationStatus Process ======== ")
343                 try{
344                         String serviceId = execution.getVariable("serviceInstanceId")
345                         String operationId = execution.getVariable("operationId")
346                         String userId = ""
347                         String result = "processing"
348                         String progress = "0"
349                         String reason = ""
350                         String operationContent = "Prepare service creation"
351                         logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId)
352                         serviceId = UriUtils.encode(serviceId,"UTF-8")
353
354                         def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
355                         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
356                         logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
357
358                         String payload =
359                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
360                         xmlns:ns="http://org.onap.so/requestsdb">
361                         <soapenv:Header/>
362                         <soapenv:Body>
363                             <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
364                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
365                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
366                             <operationType>DELETE</operationType>
367                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
368                             <result>${MsoUtils.xmlEscape(result)}</result>
369                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
370                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
371                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
372                         </ns:updateServiceOperationStatus>
373                     </soapenv:Body>
374                 </soapenv:Envelope>"""
375
376                         payload = utils.formatXml(payload)
377                         execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
378                         logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
379
380                 }catch(Exception e){
381                         logger.error("Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e)
382                         execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
383                 }
384                 logger.debug("======== COMPLETED prepareInitServiceOperationStatus Process ======== ")
385         }
386 }