Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / CreateServiceInstanceInfra.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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 com.att.bpm.scripts;
22
23 import groovy.xml.XmlUtil
24 import groovy.json.*
25
26 import org.openecomp.mso.bpmn.core.json.JsonUtils
27 import org.openecomp.mso.bpmn.core.WorkflowException
28 import org.openecomp.mso.rest.APIResponse
29 import org.openecomp.mso.rest.RESTClient
30 import org.openecomp.mso.rest.RESTConfig
31
32 import java.util.UUID;
33
34 import org.camunda.bpm.engine.delegate.BpmnError
35 import org.camunda.bpm.engine.runtime.Execution
36 import org.json.JSONObject;
37 import org.apache.commons.lang3.*
38 import org.apache.commons.codec.binary.Base64;
39
40 import org.springframework.web.util.UriUtils;
41
42 /**
43  * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process.
44  *
45  */
46 public class CreateServiceInstanceInfra extends AbstractServiceTaskProcessor {
47
48         String Prefix="CRESI_"
49         ExceptionUtil exceptionUtil = new ExceptionUtil()
50         JsonUtils jsonUtil = new JsonUtils()
51         VidUtils vidUtils = new VidUtils()
52
53         /**
54          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
55          * @param execution
56          */
57         public InitializeProcessVariables(Execution execution){
58                 /* Initialize all the process variables in this block */
59
60                 execution.setVariable("CRESI_CreateServiceInstanceJasonRequest", "")
61                 execution.setVariable("CRESI_globalSubscriberId", "")
62                 execution.setVariable("CRESI_serviceInstanceName", "")
63                 execution.setVariable("CRESI_newServiceInstanceId", "")
64                 execution.setVariable("CRESI_messageId", "")
65                 execution.setVariable("CRESI_requestId", "")
66
67                 execution.setVariable("CRESI_queryAAIGlobalCustomerIdUrlRequest", "")
68                 execution.setVariable("CRESI_queryAAIGlobalCustomerIdResponse", "")
69                 execution.setVariable("CRESI_queryAAIGlobalCustomerIdCode", "")
70
71                 execution.setVariable("CRESI_queryAAISINameUrlRequest", "")
72                 execution.setVariable("CRESI_queryAAISINamePayloadRequest", "")
73                 execution.setVariable("CRESI_queryAAISINameResponse", "")
74                 execution.setVariable("CRESI_queryAAISINameCode", "")
75
76                 execution.setVariable("CRESI_createSIinAAIUrlRequest", "")
77                 execution.setVariable("CRESI_createSIinAAIPayloadRequest", "")
78                 execution.setVariable("CRESI_createSIinAAIResponse", "")
79                 execution.setVariable("CRESI_createSIinAAICode", "")
80
81                 execution.setVariable("CRESI_createDBRequest", "")
82                 execution.setVariable("CRESI_createDBResponse", "")
83                 execution.setVariable("CRESI_createDBCode", "")
84
85                 execution.setVariable("CRESI_createDBInfraErrorRequest", "")
86                 execution.setVariable("CRESI_errorDBInfraErrorResponse", "")
87                 execution.setVariable("CRESI_errorDBInfraErrorErrorCode", "")
88
89                 execution.setVariable("CRESI_CompleteMsoProcessRequest", "")
90                 execution.setVariable("CRESI_FalloutHandlerRequest", "")
91                 execution.setVariable("CRESI_Success", false)
92                 execution.setVariable("CRESI_unexpectedError", "")
93
94         }
95
96         // **************************************************
97         //     Pre or Prepare Request Section
98         // **************************************************
99         /**
100          * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process.
101          * @param execution
102          */
103         public void preProcessRequest (Execution execution) {
104                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
105                 execution.setVariable("prefix",Prefix)
106
107                 utils.log("DEBUG", " ***** Inside preProcessRequest CreateServiceInstanceInfra Request ***** ", isDebugEnabled)
108
109                 try {
110                         // initialize flow variables
111                         InitializeProcessVariables(execution)
112
113                         // check for incoming json message/input
114                         String createServiceInstanceIncoming = execution.getVariable("bpmnRequest")
115                         utils.logAudit(createServiceInstanceIncoming)
116                         execution.setVariable("CRESI_CreateServiceInstanceJasonRequest", createServiceInstanceIncoming);
117                         println 'createServiceInstanceIncoming - ' + createServiceInstanceIncoming
118
119                         // extract requestId
120                         String requestId = execution.getVariable("att-mso-request-id")
121                         execution.setVariable("CRESI_requestId", requestId)
122
123                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
124                         execution.setVariable("serviceInstanceId", serviceInstanceId)
125
126                         String requestAction = execution.getVariable("requestAction")
127                         execution.setVariable("requestAction", requestAction)
128
129                         String source = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.requestInfo.source")
130                         execution.setVariable("CRESI_source", source)
131
132                         // extract globalSubscriberId
133                         String globalSubscriberId = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.subscriberInfo.globalSubscriberId")
134
135                         // prepare messageId
136                         String messageId = execution.getVariable("CRESI_messageId")  // for testing
137                         if (messageId == null || messageId == "") {
138                                 messageId = UUID.randomUUID()
139                                 utils.log("DEBUG", " CRESI_messageId, random generated: " + messageId, isDebugEnabled)
140                         } else {
141                                 utils.log("DEBUG", " CRESI_messageId, pre-assigned: " + messageId, isDebugEnabled)
142                         }
143                         execution.setVariable("CRESI_messageId", messageId)
144
145                         // verify element global-customer-id is sent from JSON input, throw exception if missing
146                         if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) {
147                                 String dataErrorMessage = " Element 'globalSubscriberId' is missing. "
148                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
149
150                 } else {
151                             execution.setVariable("CRESI_globalSubscriberId", globalSubscriberId)
152
153                 }
154
155                         AaiUtil aaiUriUtil = new AaiUtil(this)
156                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
157                         String aaiNamespace = aaiUriUtil.getNamespaceFromUri(aai_uri)
158                         logDebug('AAI namespace is: ' + aaiNamespace, isDebugEnabled)
159                         execution.setVariable("CRESI_aaiNamespace","${aaiNamespace}")
160
161                         String newServiceInstanceId = execution.getVariable("CRESI_testServiceInstanceId") // for testing variable
162                         if ((newServiceInstanceId) == null || (newServiceInstanceId.isEmpty())) {
163                                 newServiceInstanceId = UUID.randomUUID().toString()
164                                 utils.log("DEBUG", " Generated new Service Instance: " + newServiceInstanceId , isDebugEnabled)  // generated
165                         } else {
166                                 utils.log("DEBUG", " Assigned new Service Instance: " + newServiceInstanceId , isDebugEnabled)
167                         }
168                         newServiceInstanceId = UriUtils.encode(newServiceInstanceId,"UTF-8")
169                         execution.setVariable("CRESI_newServiceInstanceId", newServiceInstanceId)
170
171                 } catch (BpmnError e) {
172                         throw e;
173
174                 } catch (Exception ex){
175                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected from method preProcessRequest() - " + ex.getMessage()
176                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
177                 }
178
179         }
180
181         public void sendSyncResponse (Execution execution) {
182                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
183                 execution.setVariable("prefix",Prefix)
184
185                 utils.log("DEBUG", " ***** Inside sendSyncResponse of CreateServiceInstanceInfra ***** ", isDebugEnabled)
186
187                 try {
188                         String newServiceInstanceId = execution.getVariable("CRESI_newServiceInstanceId")
189                         String requestId = execution.getVariable("att-mso-request-id")
190
191                         // RESTResponse (for API Handler (APIH) Reply Task)
192                         String syncResponse ="""{"requestReferences":{"instanceId":"${newServiceInstanceId}","requestId":"${requestId}"}}""".trim()
193
194                         utils.log("DEBUG", " sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse, isDebugEnabled)
195                         sendWorkflowResponse(execution, 202, syncResponse)
196
197                 } catch (Exception ex) {
198                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected from method sendSyncResponse() - " + ex.getMessage()
199                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
200                 }
201
202         }
203
204         public void callRESTQueryAAIGlobalSubscriberId (Execution execution) {
205                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
206                 execution.setVariable("prefix",Prefix)
207
208                 utils.log("DEBUG", " ***** Inside callRESTQueryAAICustomer of CreateServiceInstanceInfra ***** " , isDebugEnabled)
209
210                 try {
211                         // get variables
212                         String messageId = execution.getVariable("CRESI_requestId")
213                         String globalSubscriberId = execution.getVariable("CRESI_globalSubscriberId")
214                         globalSubscriberId = UriUtils.encode(globalSubscriberId,"UTF-8")
215
216                         // Prepare AA&I url with globalCustomerId
217                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
218                         AaiUtil aaiUriUtil = new AaiUtil(this)
219                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
220                         String queryAAISubscriberIdUrlRequest = "${aai_endpoint}${aai_uri}/${globalSubscriberId}"
221                         utils.logAudit(queryAAISubscriberIdUrlRequest)
222                         utils.log("DEBUG", " ***** AAI Query Subscriber Id Url: " + queryAAISubscriberIdUrlRequest, isDebugEnabled)
223                         execution.setVariable("CRESI_queryAAIGlobalCustomerIdUrlRequest", queryAAISubscriberIdUrlRequest)
224
225                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
226                                                                 
227                         RESTConfig config = new RESTConfig(queryAAISubscriberIdUrlRequest);
228                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
229                                                                                                           .addHeader("X-FromAppId", "MSO")
230                                                                                                           .addHeader("Content-Type", "application/xml")
231                                                                                                           .addHeader("Accept","application/xml");
232                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
233                                 client.addAuthorizationHeader(basicAuthCred)
234                         }
235                         APIResponse response = client.get()
236                         String returnCode = response.getStatusCode()
237                         execution.setVariable("CRESI_queryAAIGlobalCustomerIdCode", returnCode)
238                         utils.log("DEBUG", " ***** AAI Query Customer Subscriber Id Response Code  : " + returnCode, isDebugEnabled)
239
240                         String aaiResponseAsString = response.getResponseBodyAsString()
241                         execution.setVariable("CRESI_queryAAIGlobalCustomerIdResponse", aaiResponseAsString)
242                         utils.logAudit(aaiResponseAsString)
243
244                         if (returnCode=='200') {
245                                 // Customer found by ID. FLow to proceed.
246                                 utils.log("DEBUG", " CRESI_queryAAIGlobalCustomerIdResponse  : " + aaiResponseAsString, isDebugEnabled)
247
248                                 //TODO
249                                 //we might verify that service-subscription with matching name exists
250                                 //and throw error if not. If not checked, we will get exception in subsequent step on Create call
251                                 //in 1610 we assume both customer & service subscription were pre-created
252
253                         } else {
254                                 if (returnCode=='404') {
255                                         String errorMessage = " Customer Global Id not found (404) in AAI, Global Subscriber id: " + globalSubscriberId
256                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
257
258                                 } else {
259                                         if (aaiResponseAsString.contains("RESTFault")) {
260                                                 // build WorkflowException & throw new BpmnError("MSOWorkflowException")
261                                                 WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
262                                                 execution.setVariable("WorkflowException", workflowException)
263                                                 throw new BpmnError("MSOWorkflowException")
264
265                                         } else {
266                                                 // aai all errors
267                                                 String errorMessage = " Unexpected Error Response from AAI during callRESTQueryAAICustomerSubcriberId() - " + returnCode
268                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage)
269                                         }
270
271                                 }
272                         }
273
274                 } catch (BpmnError e) {
275                         throw e;
276
277                 } catch (Exception ex) {
278                         // try error in method block
279                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error during method callRESTQueryAAICustomerSubcriberId() - " + ex.getMessage()
280                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
281                 }
282
283         }
284
285
286         public void callRESTQueryAAISIName (Execution execution) {
287                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
288                 execution.setVariable("prefix",Prefix)
289
290                 utils.log("DEBUG", " ***** Inside callRESTQueryAAISIName of CreateServiceInstanceInfra ***** " , isDebugEnabled)
291
292                 try {
293                         // get variables
294                         String messageId = execution.getVariable("CRESI_requestId")
295                         String globalSubscriberId = execution.getVariable("CRESI_globalSubscriberId")
296                         globalSubscriberId = UriUtils.encode(globalSubscriberId,"UTF-8")
297
298                         // extract serviceType
299                         String createServiceInstanceIncoming = execution.getVariable("CRESI_CreateServiceInstanceJasonRequest");
300                         String serviceInstanceName = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.requestInfo.instanceName")
301                         serviceInstanceName = UriUtils.encode(serviceInstanceName,'UTF-8')
302                         String serviceType = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.modelInfo.modelName")
303                         serviceType = UriUtils.encode(serviceType,'UTF-8')
304
305                         // Prepare AA&I url
306                         //String aai_endpoint = execution.getVariable("URN_aai_endpoint")
307                         AaiUtil aaiUriUtil = new AaiUtil(this)
308                         String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
309
310                         // seach by service instance name
311
312                         // Currently not designed, but this would search for service-instance-name within realm of customer:
313                         // https://{serverURL}/aai/{version}/business/customers/customer/{globalCustID}/service-subscriptions/service-subscription/{serviceType}/service-instances?service-instance-name={serviceInstanceName}
314                         //search for service-instance-name globally:
315                         String queryAAISINameUrlRequest = "${aai_uri}?search-node-type=service-instance&filter=service-instance-name:EQUALS:${serviceInstanceName}"
316                         utils.log("DEBUG", " ***** AAI Query Service Name Url: " + queryAAISINameUrlRequest, isDebugEnabled)
317
318                         utils.logAudit(queryAAISINameUrlRequest)
319                         execution.setVariable("CRESI_queryAAISINameUrlRequest", queryAAISINameUrlRequest)
320
321                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
322                                                                         
323                         RESTConfig config = new RESTConfig(queryAAISINameUrlRequest);
324                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
325                                                                                                           .addHeader("X-FromAppId", "MSO")
326                                                                                                           .addHeader("Content-Type", "application/xml")
327                                                                                                           .addHeader("Accept","application/xml");
328                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
329                                 client.addAuthorizationHeader(basicAuthCred)
330                         }
331                         APIResponse response = client.get()
332                         String returnCode = response.getStatusCode()
333                         execution.setVariable("CRESI_queryAAISINameCode", returnCode)
334                         utils.log("DEBUG", " ***** AAI Query Service Instance Name Response Code  : " + returnCode, isDebugEnabled)
335
336                         String aaiResponseAsString = response.getResponseBodyAsString()
337                         utils.log("DEBUG", " ***** AAI Query Service Instance Name Response : " +'\n'+ aaiResponseAsString, isDebugEnabled)
338
339                         if (returnCode=='200') {
340                                 utils.logAudit(aaiResponseAsString)
341                                 execution.setVariable("CRESI_queryAAISINameResponse", aaiResponseAsString)
342
343                                 if ( (aaiResponseAsString != null) && (aaiResponseAsString.contains("service-instance")) ) {
344                                         // SI with same name was found
345                                         serviceInstanceName = UriUtils.decode(serviceInstanceName,'UTF-8')
346                                         String errorMessage = " Stopped creating Service Instance, already exists in AAI. Service instance name: " + serviceInstanceName
347                                         utils.log("DEBUG", errorMessage, isDebugEnabled)
348                                         exceptionUtil.buildWorkflowException(execution, 2500, errorMessage)
349                                 } else {
350                                         utils.log("DEBUG", "AAI return code 200, but no content found matching ServiceInstance name", isDebugEnabled)
351                                         //Actual meaning is 404 Not Found
352                                         execution.setVariable("CRESI_queryAAISINameCode", '404')
353                                 }
354
355                         } else {
356                             if (returnCode=='404') {
357                                         utils.log("DEBUG", " AAI Query return code = '404'. Proceed with the Create Service Instance !!! ", isDebugEnabled)
358
359                             } else {
360                                         if (aaiResponseAsString.contains("RESTFault")) {
361                                                 // build WorkflowException
362                                                 WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
363                                                 execution.setVariable("WorkflowException", workflowException)
364
365                                         } else {
366                                         // aai all errors
367                                                 String errorMessage = " Unexpected Error Response from AAI  during callRESTQueryAAISIName() - " + returnCode
368                                                 exceptionUtil.buildWorkflowException(execution, 2500, errorMessage)
369                                         }
370                       }
371
372                         }
373
374                 } catch (BpmnError e) {
375                         throw e;
376
377                 } catch (Exception excp) {
378                         // try error for method block
379                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow in method callRESTQueryAAISIName(). Error was - " + excp.getMessage()
380                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
381
382                 }
383
384         }
385
386         public void callRESTCreateServiceInstanceInAAI(Execution execution) {
387                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
388                 execution.setVariable("prefix", Prefix)
389
390                 utils.log("DEBUG", " ***** Inside callRESTCreateServiceInstanceInAAI of CreateServiceInstanceInfra ***** " , isDebugEnabled)
391
392                 try {
393
394                         // get variables
395                         String messageId = execution.getVariable("CRESI_messageId")
396                         String newServiceInstanceId = execution.getVariable("CRESI_newServiceInstanceId")
397
398                         String globalSubcriberId = execution.getVariable("CRESI_globalSubscriberId")
399                         globalSubcriberId = UriUtils.encode(globalSubcriberId,"UTF-8")
400
401                         // get variable within incoming json
402                         String createServiceInstanceIncoming = execution.getVariable("CRESI_CreateServiceInstanceJasonRequest");
403                         String serviceType = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.requestParameters.subscriptionServiceType")
404                         if (serviceType != null || serviceType != "") {
405                                 serviceType = UriUtils.encode(serviceType,"UTF-8")
406                         }
407
408                         String personaModelId = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.modelInfo.modelInvariantId")
409                         String personaModelVersion = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.modelInfo.modelVersion")
410                         String workloadContext = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.modelInfo.workload-context")
411
412                         String serviceInstanceName = jsonUtil.getJsonValue(createServiceInstanceIncoming, "requestDetails.requestInfo.instanceName")
413
414                         // Prepare url
415                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
416                         AaiUtil aaiUriUtil = new AaiUtil(this)
417                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
418                         String createServiceInstanceAAIUrlRequest = "${aai_endpoint}${aai_uri}/${globalSubcriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${newServiceInstanceId}"
419                         utils.log("DEBUG", " ***** AAI Create Service Instance Url: " + createServiceInstanceAAIUrlRequest, isDebugEnabled)
420
421                         utils.logAudit(createServiceInstanceAAIUrlRequest)
422                         execution.setVariable("CRESI_createSIinAAIUrlRequest", createServiceInstanceAAIUrlRequest)
423
424                         //Prepare payload (PUT)
425                         String schemaVersion = aaiUriUtil.getNamespaceFromUri(aai_uri)
426
427                         String createServiceInstancePayload =
428                         """<service-instance xmlns="${execution.getVariable("CRESI_aaiNamespace")}">
429                                 <service-instance-name>${serviceInstanceName}</service-instance-name>
430                                 <persona-model-id>${personaModelId}</persona-model-id>
431                                 <persona-model-version>${personaModelVersion}</persona-model-version>
432                                 </service-instance>
433                                 """.trim()
434
435                         utils.logAudit(createServiceInstancePayload)
436                         execution.setVariable("CRESI_createSIinAAIPayloadRequest", createServiceInstancePayload)
437                         utils.log("DEBUG", " 'payload' to create Service Instance in AAI - " + "\n" + createServiceInstancePayload, isDebugEnabled)
438
439                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
440                                                                         
441                         RESTConfig config = new RESTConfig(createServiceInstanceAAIUrlRequest);
442                         RESTClient client = new RESTClient(config).addHeader("X-TransactionId", messageId)
443                                                                                                           .addHeader("X-FromAppId", "MSO")
444                                                                                                           .addHeader("Content-Type", "application/xml")
445                                                                                                           .addHeader("Accept","application/xml");
446                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
447                                 client.addAuthorizationHeader(basicAuthCred)
448                         }
449                         APIResponse response = client.httpPut(createServiceInstancePayload)
450                         String returnCode = response.getStatusCode()
451                         execution.setVariable("CRESI_createSIinAAICode", returnCode)
452                         utils.log("DEBUG", " ***** AAI Create Service Instance Response Code : " + returnCode, isDebugEnabled)
453
454                         String aaiResponseAsString = response.getResponseBodyAsString()
455                         utils.logAudit(aaiResponseAsString)
456
457                         if (returnCode.toInteger() > 199 && returnCode.toInteger() < 203) {
458                                 //200 OK 201 CREATED 202 ACCEPTED
459                                 utils.log("DEBUG", " AAI Create Service Instance Success REST Response.", isDebugEnabled)
460
461                         } else {
462                                 if (returnCode=='404') {
463                                         String dataErrorMessage = " AAI Create Service Instance Failed, Error 404. Proposed new Create Instance Id was: " + newServiceInstanceId
464                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
465
466                                 } else {
467                                    if (aaiResponseAsString.contains("RESTFault")) {
468                                            // build WorkflowException & throw new BpmnError("MSOWorkflowException")
469                                            WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
470                                            execution.setVariable("WorkflowException", workflowException)
471                                            throw new BpmnError("MSOWorkflowException")
472
473                                            } else {
474                                                         // aai all errors
475                                                         String dataErrorMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error during create call in AAI - " + returnCode
476                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
477                                           }
478                                 }
479                         }
480
481                 } catch (BpmnError e) {
482                 throw e;
483
484                 } catch (Exception excep) {
485                         // try error in method block
486                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error from method callRESTCreateServiceInstanceInAAI() - " + excep.getMessage()
487                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
488
489                 }
490
491         }
492
493         // *******************************
494         //     Build DB request Section
495         // *******************************
496         public void prepareDBRequest (Execution execution) {
497                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
498                 execution.setVariable("prefix", Prefix)
499
500                 try {
501                         utils.log("DEBUG", " ***** Inside prepareDBRequest of CreateServiceInstanceInfra ***** ", isDebugEnabled)
502
503                         String requestId = execution.getVariable("CRESI_requestId")
504                         String statusMessage = "Service Instance successfully created."
505                         String serviceInstanceId = execution.getVariable("CRESI_newServiceInstanceId")
506
507                         //TODO - verify the format for Service Instance Create,
508                         String dbRequest =
509                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
510                                                 <soapenv:Header/>
511                                                 <soapenv:Body>
512                                                         <ns:updateInfraRequest xmlns:ns="http://com.att.mso/requestsdb">
513                                                                 <requestId>${requestId}</requestId>
514                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
515                                                                 <statusMessage>${statusMessage}</statusMessage>
516                                                                 <responseBody></responseBody>
517                                                                 <requestStatus>COMPLETED</requestStatus>
518                                                                 <progress>100</progress>
519                                                                 <vnfOutputs/>
520                                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
521                                                         </ns:updateInfraRequest>
522                                                 </soapenv:Body>
523                                            </soapenv:Envelope>"""
524
525                    String buildDeleteDBRequestAsString = utils.formatXml(dbRequest)
526                    execution.setVariable("CRESI_createDBRequest", buildDeleteDBRequestAsString)
527                    utils.logAudit(buildDeleteDBRequestAsString)
528
529                 } catch (Exception ex) {
530                         // try error in method block
531                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage()
532                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
533
534                 }
535
536          }
537
538
539         // *****************************************
540         //     Prepare Completion request Section
541         // *****************************************
542         public void postProcessResponse (Execution execution) {
543                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
544                 execution.setVariable("prefix", Prefix)
545
546                 utils.log("DEBUG", " ***** Inside postProcessResponse of CreateNetworkInstanceInfra ***** ", isDebugEnabled)
547
548                 try {
549                         // Display Success scenario for DB update Response:
550                         String dbReturnCode = execution.getVariable("CRESI_createDBCode")
551                         utils.log("DEBUG", " ***** Success DB Update Response Code  : " + dbReturnCode, isDebugEnabled)
552                         utils.log("DEBUG", " ***** Success DB Update Response String: " + '\n' + execution.getVariable("CRESI_createDBResponse"), isDebugEnabled)
553
554                         if (dbReturnCode == "200") {
555                                 String source = execution.getVariable("CRESI_source")
556                                 String requestId = execution.getVariable("CRESI_requestId")
557
558                                 String msoCompletionRequest =
559                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
560                                                                         xmlns:ns="http://ecomp.att.com/mso/request/types/v1">
561                                                         <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
562                                                                 <request-id>${requestId}</request-id>
563                                                                 <action>CREATE</action>
564                                                                 <source>${source}</source>
565                                                         </request-info>
566                                                         <aetgt:status-message>Service Instance has been created successfully.</aetgt:status-message>
567                                                         <aetgt:mso-bpel-name>BPMN Service Instance action: CREATE</aetgt:mso-bpel-name>
568                                                 </aetgt:MsoCompletionRequest>"""
569
570                                         // Format Response
571                                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
572
573                                         utils.logAudit(xmlMsoCompletionRequest)
574                                         execution.setVariable("CRESI_Success", true)
575                                         execution.setVariable("CRESI_CompleteMsoProcessRequest", xmlMsoCompletionRequest)
576                                         utils.log("DEBUG", " SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
577
578                         } else {
579                                 String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error from DB adapter, return code: " + dbReturnCode
580                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, exceptionMessage)
581
582                         }
583
584                 } catch (BpmnError e) {
585                 throw e;
586
587                 } catch (Exception ex) {
588                         // try error in method block
589                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage()
590                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
591
592                 }
593
594         }
595
596
597         // *******************************
598         //     Build Error Section
599         // *******************************
600         public void prepareDBRequestError (Execution execution) {
601                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
602                 execution.setVariable("prefix", Prefix)
603
604                 utils.log("DEBUG", " ***** Inside prepareDBRequestError of CreateServiceInstanceInfra ***** ", isDebugEnabled)
605
606                 try {
607                         String requestId = execution.getVariable("CRESI_requestId")
608                         String statusMessage = ""
609                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
610                                 WorkflowException wfe = execution.getVariable("WorkflowException")
611                                 statusMessage = wfe.getErrorMessage()
612
613                         } else {
614                                 statusMessage = "Encountered Error during CreateServiceInstance proccessing. "
615                         }
616
617                         //TODO - verify the format for Service Instance Create,
618                         String dbRequest =
619                                         """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
620                                                 <soapenv:Header/>
621                                                 <soapenv:Body>
622                                                         <ns:updateInfraRequest xmlns:ns="http://com.att.mso/requestsdb">
623                                                                 <requestId>${requestId}</requestId>
624                                                                 <lastModifiedBy>BPMN</lastModifiedBy>
625                                                                 <statusMessage>${statusMessage}</statusMessage>
626                                                                 <responseBody></responseBody>
627                                                                 <requestStatus>FAILED</requestStatus>
628                                                                 <vnfOutputs/>
629                                                         </ns:updateInfraRequest>
630                                                 </soapenv:Body>
631                                            </soapenv:Envelope>"""
632
633                    String buildDBRequestAsString = utils.formatXml(dbRequest)
634                    execution.setVariable("CRESI_createDBInfraErrorRequest", buildDBRequestAsString)
635                    utils.logAudit(buildDBRequestAsString)
636
637                 } catch (Exception ex) {
638                         // try error in method block
639                         String exceptionMessage = "Bpmn error encountered in CreateServiceInstanceInfra flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage()
640                         exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage)
641
642                 }
643
644          }
645
646         // Prepare for FalloutHandler
647         public void buildErrorResponse (Execution execution) {
648                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
649                 execution.setVariable("prefix", Prefix)
650
651                 utils.log("ERROR", " ***** Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. *****", isDebugEnabled)
652
653                 String falloutHandlerRequest = ""
654                 try {
655                         // Display Success scenario for DB update Response:
656                         String dbReturnCode = execution.getVariable("CRESI_errorDBInfraErrorErrorCode")
657                         utils.log("DEBUG", " ***** Error DB Update Response Code  : " + dbReturnCode, isDebugEnabled)
658                         utils.log("DEBUG", " ***** Error DB Update Response String: " + '\n' + execution.getVariable("CRESI_errorDBInfraErrorResponse"), isDebugEnabled)
659
660                         String requestId = execution.getVariable("CRESI_requestId")
661                         String source = execution.getVariable("CRESI_source")
662
663                         execution.setVariable("CRESI_Success", false)
664                         String errorMessage = ""
665                         String errorCode = ""
666
667                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
668                                 WorkflowException wfe = execution.getVariable("WorkflowException")
669                                 errorMessage = wfe.getErrorMessage()
670                                 errorCode = wfe.getErrorCode().toString()
671
672                         } else {
673                                 errorMessage = "Bpmn error encountered in CreateServiceInstance flow."
674                                 errorCode = "2500"
675
676                         }
677
678                         falloutHandlerRequest =
679                                 """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
680                                                                      xmlns:ns="http://ecomp.att.com/mso/request/types/v1"
681                                                                      xmlns:wfsch="http://ecomp.att.com/mso/workflow/schema/v1">
682                                            <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
683                                               <request-id>${requestId}</request-id>
684                                               <action>CREATE</action>
685                                               <source>${source}</source>
686                                            </request-info>
687                                                 <aetgt:WorkflowException xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1">
688                                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
689                                                         <aetgt:ErrorCode>${errorCode}</aetgt:ErrorCode>
690                                                 </aetgt:WorkflowException>
691                                         </aetgt:FalloutHandlerRequest>"""
692
693                         utils.logAudit(falloutHandlerRequest)
694                         execution.setVariable("CRESI_FalloutHandlerRequest", falloutHandlerRequest)
695                         utils.log("ERROR", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
696
697                 } catch (Exception ex) {
698                         // rebuild workflow exception
699                         String requestId = execution.getVariable("CRESI_requestId")
700                         String source = execution.getVariable("CRESI_source")
701                         String errorException = " Build Error Response exception encountered during method buildErrorResponse(), preparing request for FalloutHandler: - " + ex.getMessage()
702                         utils.log("DEBUG", errorException, isDebugEnabled)
703                         falloutHandlerRequest =
704                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1"
705                                                                      xmlns:ns="http://ecomp.att.com/mso/request/types/v1"
706                                                                      xmlns:wfsch="http://ecomp.att.com/mso/workflow/schema/v1">
707                                            <request-info xmlns="http://ecomp.att.com/mso/infra/vnf-request/v1">
708                                               <request-id>${requestId}</request-id>
709                                               <action>CREATE</action>
710                                               <source>${source}</source>
711                                            </request-info>
712                                                 <aetgt:WorkflowException xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1">
713                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
714                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
715                                                 </aetgt:WorkflowException>
716                                         </aetgt:FalloutHandlerRequest>"""
717                         execution.setVariable("CRESI_FalloutHandlerRequest", falloutHandlerRequest)
718                         utils.log("ERROR", "  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest, isDebugEnabled)
719
720                 }
721
722         }
723
724         public void sendSyncError (Execution execution) {
725                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
726                 execution.setVariable("prefix", Prefix)
727
728                 utils.log("DEBUG", " ***** Inside sendSyncError() of CreateServiceInstanceInfra ***** ", isDebugEnabled)
729
730                 try {
731                         String errorMessage = ""
732                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
733                                 WorkflowException wfe = execution.getVariable("WorkflowException")
734                                 errorMessage = wfe.getErrorMessage()
735                         } else {
736                                 errorMessage = "Sending Sync Error."
737                         }
738
739                         String buildworkflowException =
740                                 """<aetgt:WorkflowException xmlns:aetgt="http://ecomp.att.com/mso/workflow/schema/v1">
741                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
742                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
743                                    </aetgt:WorkflowException>"""
744
745                         utils.logAudit(buildworkflowException)
746                         sendWorkflowResponse(execution, 500, buildworkflowException)
747
748
749                 } catch (Exception ex) {
750                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
751                 }
752
753         }
754
755         public void processJavaException(Execution execution){
756                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
757                 execution.setVariable("prefix",Prefix)
758                 try{
759                         utils.log("DEBUG", "Caught a Java Exception", isDebugEnabled)
760                         utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled)
761                         utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
762                         execution.setVariable("CRESI_unexpectedError", "Caught a Java Lang Exception")  // Adding this line temporarily until this flows error handling gets updated
763                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception")
764                 }catch(BpmnError b){
765                         utils.log("ERROR", "Rethrowing MSOWorkflowException", isDebugEnabled)
766                         throw b
767                 }catch(Exception e){
768                         utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled)
769                         execution.setVariable("CRESI_unexpectedError", "Exception in processJavaException method")  // Adding this line temporarily until this flows error handling gets updated
770                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method")
771                 }
772                 utils.log("DEBUG", "Completed processJavaException Method", isDebugEnabled)
773         }
774
775
776 }