AT&T 1712 and 1802 release code
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DeleteGenericALaCarteServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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 package org.openecomp.mso.bpmn.infrastructure.scripts;
21
22 import groovy.xml.XmlUtil
23 import groovy.json.*
24
25 import org.openecomp.mso.bpmn.core.json.JsonUtils
26 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
28 import org.openecomp.mso.bpmn.common.scripts.VidUtils
29 import org.openecomp.mso.bpmn.core.WorkflowException
30 import org.openecomp.mso.rest.APIResponse;
31
32 import java.util.UUID;
33 import javax.xml.parsers.DocumentBuilder
34 import javax.xml.parsers.DocumentBuilderFactory
35
36 import org.camunda.bpm.engine.delegate.BpmnError
37 import org.camunda.bpm.engine.delegate.DelegateExecution
38 import org.json.JSONObject;
39 import org.apache.commons.lang3.*
40 import org.apache.commons.codec.binary.Base64;
41 import org.w3c.dom.Document
42 import org.w3c.dom.Element
43 import org.w3c.dom.Node
44 import org.w3c.dom.NodeList
45 import org.xml.sax.InputSource
46 import static org.apache.commons.lang3.StringUtils.*;
47
48 import org.springframework.web.util.UriUtils;
49
50 /**
51  * This groovy class supports the <class>DelServiceInstance.bpmn</class> process.
52  *
53  */
54 public class DeleteGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor {
55
56         String Prefix="DELSI_"
57         ExceptionUtil exceptionUtil = new ExceptionUtil()
58         JsonUtils jsonUtil = new JsonUtils()
59         VidUtils vidUtils = new VidUtils()
60         
61         public void preProcessRequest (DelegateExecution execution) {
62                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
63                 execution.setVariable("prefix",Prefix)
64                 String msg = ""
65                 
66                 utils.log("DEBUG", " *** preProcessRequest Request *** ", isDebugEnabled)
67
68                 try {
69                         // check for incoming json message/input
70                         String siRequest = execution.getVariable("bpmnRequest")
71                         utils.logAudit(siRequest)
72                         
73
74                         String requestId = execution.getVariable("mso-request-id")
75                         execution.setVariable("msoRequestId", requestId)
76                         utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
77                         
78                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
79                         if (isBlank(serviceInstanceId)) {
80                                 msg = "Input serviceInstanceId' is null"
81                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
82                         }
83                 
84                         //String xmlRequestDetails = vidUtils.getJsonRequestDetailstoXml(siRequest)
85                         //execution.setVariable("requestDetails", xmlRequestDetails)
86                         
87                         //modelInfo
88                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
89                         if (isBlank(serviceModelInfo)) {
90                                 msg = "Input serviceModelInfo is null"
91                                 utils.log("DEBUG", msg, isDebugEnabled)
92                         } else
93                         {
94                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
95                                 //utils.log("DEBUG", "modelInfo" + serviceModelInfo,  isDebugEnabled)
96                         }
97                         
98                         //requestInfo
99                         String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
100                         if (isBlank(productFamilyId))
101                         {
102                                 msg = "Input productFamilyId is null"
103                                 utils.log("DEBUG", msg, isDebugEnabled)
104                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
105                         } else {
106                                 execution.setVariable("productFamilyId", productFamilyId)
107                         }
108                         String source = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")
109                         execution.setVariable("source", source)
110                         
111                         //subscriberInfo
112                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
113                         if (isBlank(globalSubscriberId)) {
114                                 msg = "Input globalSubscriberId' is null"
115                                 utils.log("DEBUG", msg, isDebugEnabled)
116                         } else {
117                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
118                         }
119                         
120                         //requestParameters
121                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
122                         if (isBlank(subscriptionServiceType)) {
123                                 msg = "Input subscriptionServiceType is null"
124                                 utils.log("DEBUG", msg, isDebugEnabled)
125                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
126                         } else {
127                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
128                         }
129                         
130                         /*
131                          * Extracting User Parameters from incoming Request and converting into a Map
132                          */
133                         def jsonSlurper = new JsonSlurper()
134                         def jsonOutput = new JsonOutput()
135
136                         Map reqMap = jsonSlurper.parseText(siRequest)
137
138                         //InputParams
139                         def userParams = reqMap.requestDetails?.requestParameters?.userParams
140
141                         Map<String, String> inputMap = [:]
142                         if (userParams) {
143                                 userParams.each {
144                                         userParam -> inputMap.put(userParam.name, userParam.value.toString())
145                                 }
146                         }
147                         
148                         utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled)
149                         execution.setVariable("serviceInputParams", inputMap)
150
151                 } catch (BpmnError e) {
152                         throw e;
153                 } catch (Exception ex){
154                         msg = "Exception in preProcessRequest " + ex.getMessage()
155                         utils.log("DEBUG", msg, isDebugEnabled)
156                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
157                 }
158                 utils.log("DEBUG"," ***** Exit preProcessRequest *****",  isDebugEnabled)
159         }
160
161         public void sendSyncResponse (DelegateExecution execution) {
162                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
163                 utils.log("DEBUG", " *** sendSyncResponse  *** ", isDebugEnabled)
164
165                 try {
166                         String requestId = execution.getVariable("msoRequestId")
167                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
168
169                         // RESTResponse (for API Handler (APIH) Reply Task)
170                         String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
171                         utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled)
172                         sendWorkflowResponse(execution, 202, syncResponse)
173
174                 } catch (Exception ex) {
175                         String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
176                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
177                 }
178                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
179         }
180         
181         public void sendSyncError (DelegateExecution execution) {
182                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
183                 utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled)
184
185                 try {
186                         String errorMessage = ""
187                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
188                                 WorkflowException wfe = execution.getVariable("WorkflowException")
189                                 errorMessage = wfe.getErrorMessage()
190                         } else {
191                                 errorMessage = "Sending Sync Error."
192                         }
193
194                         String buildworkflowException =
195                                 """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
196                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
197                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
198                                    </aetgt:WorkflowException>"""
199
200                         utils.logAudit(buildworkflowException)
201                         sendWorkflowResponse(execution, 500, buildworkflowException)
202
203                 } catch (Exception ex) {
204                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
205                 }
206
207         }
208         
209         public void prepareCompletionRequest (DelegateExecution execution) {
210                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
211                 utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled)
212
213                 try {
214                         String requestId = execution.getVariable("msoRequestId")
215                         String source = execution.getVariable("source")
216                         String msoCompletionRequest =
217                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
218                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">
219                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
220                                                         <request-id>${requestId}</request-id>
221                                                         <action>DELETE</action>
222                                                         <source>${source}</source>
223                                                 </request-info>
224                                                 <aetgt:status-message>Service Instance was deleted successfully.</aetgt:status-message>
225                                                 <aetgt:mso-bpel-name>DeleteGenericALaCarteServiceInstance</aetgt:mso-bpel-name>
226                                         </aetgt:MsoCompletionRequest>"""
227
228                         // Format Response
229                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
230
231                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
232                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
233
234                 } catch (Exception ex) {
235                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
236                         utils.log("DEBUG", msg, isDebugEnabled)
237                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
238                 }
239                 utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
240         }
241         
242         public void prepareFalloutRequest(DelegateExecution execution){
243                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
244                 utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled)
245
246                 try {
247                         WorkflowException wfex = execution.getVariable("WorkflowException")
248                         utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
249                         String requestId = execution.getVariable("msoRequestId")
250                         String source = execution.getVariable("source")
251                         String requestInfo =
252                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
253                                         <request-id>${requestId}</request-id>
254                                         <action>DELETE</action>
255                                         <source>${source}</source>
256                                    </request-info>"""
257
258                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
259                         execution.setVariable("falloutRequest", falloutRequest)
260                 } catch (Exception ex) {
261                         utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
262                         String errorException = "  Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
263                         String requestId = execution.getVariable("msoRequestId")
264                         String falloutRequest =
265                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
266                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"
267                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
268                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
269                                               <request-id>${requestId}</request-id>
270                                               <action>DELETE</action>
271                                               <source>VID</source>
272                                            </request-info>
273                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
274                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
275                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
276                                                 </aetgt:WorkflowException>
277                                         </aetgt:FalloutHandlerRequest>"""
278
279                         execution.setVariable("falloutRequest", falloutRequest)
280                 }
281                 utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
282         }
283         
284
285         // *******************************
286         //     Build DB request Section
287         // *******************************
288         public void prepareDBRequest (DelegateExecution execution) {
289                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
290                 execution.setVariable("prefix", Prefix)
291
292                 try {
293                         utils.log("DEBUG", " ***** Inside prepareDBRequest of DeleteGenericALaCarteServiceInstance ***** ", isDebugEnabled)
294
295                         String requestId = execution.getVariable("DELSI_requestId")
296                         String statusMessage = "Service Instance successfully deleted."
297
298                         //TODO - verify the format for Service Instance Delete,
299                         String dbRequest =
300                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
301                                                 <soapenv:Header/>
302                                                 <soapenv:Body>
303                                                         <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
304                                                                 <requestId>${requestId}</requestId>
305                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
306                                                                 <statusMessage>${statusMessage}</statusMessage>
307                                                                 <responseBody></responseBody>
308                                                                 <requestStatus>COMPLETED</requestStatus>
309                                                                 <progress>100</progress>
310                                                         </ns:updateInfraRequest>
311                                                    </soapenv:Body>
312                                            </soapenv:Envelope>"""
313
314                    String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
315                    execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString)
316                    utils.logAudit(buildDeleteDBRequestAsString)
317
318                 } catch (Exception ex) {
319                         // try error in method block
320                         String exceptionMessage = "Bpmn error encountered in DeleteGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage()
321                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
322
323                 }
324
325          }
326
327         // *******************************
328         //     Build Error Section
329         // *******************************
330         public void prepareDBRequestError (DelegateExecution execution) {
331                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
332                 execution.setVariable("prefix", Prefix)
333
334                 utils.log("DEBUG", " ***** Inside prepareDBRequestError of DeleteGenericALaCarteServiceInstance ***** ", isDebugEnabled)
335
336                 try {
337                         String requestId = execution.getVariable("DELSI_requestId")
338                         String statusMessage = ""
339                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
340                                 WorkflowException wfe = execution.getVariable("WorkflowException")
341                                 statusMessage = wfe.getErrorMessage()
342
343                         } else {
344                                 statusMessage = "Encountered Error during DeleteGenericALaCarteServiceInstance proccessing. "
345                         }
346
347                         //TODO - verify the format for Service Instance Create,
348                         String dbRequest =
349                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
350                                                 <soapenv:Header/>
351                                                 <soapenv:Body>
352                                                         <ns:updateInfraRequest xmlns:ns="http://org.openecomp.mso/requestsdb">
353                                                                 <requestId>${requestId}</requestId>
354                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
355                                                                 <statusMessage>${statusMessage}</statusMessage>
356                                                                 <responseBody></responseBody>
357                                                                 <requestStatus>FAILED</requestStatus>
358                                                         </ns:updateInfraRequest>
359                                                    </soapenv:Body>
360                                            </soapenv:Envelope>"""
361
362                    String buildDBRequestAsString = utils.formatXml(dbRequest)
363                    execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString)
364                    utils.logAudit(buildDBRequestAsString)
365
366                 } catch (Exception ex) {
367                         // try error in method block
368                         String exceptionMessage = "Bpmn error encountered in DeleteGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage()
369                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
370
371                 }
372
373          }
374 }