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