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