Merge "Reorder modifiers"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoCreateServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.mso.bpmn.infrastructure.scripts;
21
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.openecomp.mso.bpmn.common.scripts.AaiUtil
25 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.openecomp.mso.bpmn.common.scripts.CatalogDbUtils
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
28 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils
29 import org.openecomp.mso.bpmn.core.RollbackData
30 import org.openecomp.mso.bpmn.core.WorkflowException
31 import org.openecomp.mso.bpmn.core.domain.ModelInfo
32 import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition
33 import org.openecomp.mso.bpmn.core.domain.ServiceInstance
34 import org.openecomp.mso.bpmn.core.json.JsonUtils
35 import org.openecomp.mso.bpmn.infrastructure.aai.AAICreateResources
36 import org.openecomp.mso.rest.APIResponse
37 import org.springframework.web.util.UriUtils
38
39 import static org.apache.commons.lang3.StringUtils.*;
40 import groovy.xml.XmlUtil
41 import groovy.json.*
42
43 import org.openecomp.mso.rest.RESTClient
44 import org.openecomp.mso.rest.RESTConfig
45 import org.openecomp.mso.client.aai.AAIResourcesClient
46
47 import java.util.logging.Logger;
48 import java.net.URI;
49
50 import java.util.UUID;
51
52 import org.camunda.bpm.engine.delegate.BpmnError
53 import org.camunda.bpm.engine.delegate.DelegateExecution
54 import org.json.JSONObject;
55 import org.apache.commons.lang3.*
56 import org.apache.commons.codec.binary.Base64;
57 import org.springframework.web.util.UriUtils;
58
59 /**
60  * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process.
61  *
62  * Inputs:
63  * @param - msoRequestId
64  * @param - globalSubscriberId
65  * @param - subscriptionServiceType
66  * @param - serviceInstanceId
67  * @param - serviceInstanceName - O
68  * @param - serviceModelInfo
69  * @param - productFamilyId
70  * @param - disableRollback
71  * @param - failExists - TODO
72  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
73  * @param - sdncVersion ("1610")
74  * @param - serviceDecomposition - Decomposition for R1710 
75  * (if macro provides serviceDecompsition then serviceModelInfo, serviceInstanceId & serviceInstanceName will be ignored)
76  *
77  * Outputs:
78  * @param - rollbackData (localRB->null)
79  * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true)
80  * @param - WorkflowException
81  * @param - serviceInstanceName - (GET from AAI if null in input)
82  *
83  * This BB processes Macros(except TRANSPORT all sent to sdnc) and Alacartes(sdncSvcs && nonSdncSvcs) 
84  */
85 public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
86
87         String Prefix="DCRESI_"
88         ExceptionUtil exceptionUtil = new ExceptionUtil()
89         JsonUtils jsonUtil = new JsonUtils()
90         CatalogDbUtils cutils = new CatalogDbUtils()
91
92         public void preProcessRequest (DelegateExecution execution) {
93                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
94                 String msg = ""
95                 utils.log("DEBUG"," ***** preProcessRequest *****",  isDebugEnabled)
96
97                 try {
98                         String requestId = execution.getVariable("msoRequestId")
99                         execution.setVariable("prefix", Prefix)
100                         
101                         //Inputs
102                         //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
103                         String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
104
105                         //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
106                         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
107
108                         //requestDetails.requestParameters. for SDNC assignTopology
109                         String productFamilyId = execution.getVariable("productFamilyId") //AAI productFamilyId
110
111                         if (isBlank(globalSubscriberId)) {
112                                 msg = "Input globalSubscriberId is null"
113                                 utils.log("DEBUG", msg, isDebugEnabled)
114                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
115                         }
116                         
117                         if (isBlank(subscriptionServiceType)) {
118                                 msg = "Input subscriptionServiceType is null"
119                                 utils.log("DEBUG", msg, isDebugEnabled)
120                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
121                         }
122                         
123                         if (productFamilyId == null) {
124                                 execution.setVariable("productFamilyId", "")
125                         }
126                         
127                         String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback')
128                         if (isBlank(sdncCallbackUrl)) {
129                                 msg = "URN_mso_workflow_sdncadapter_callback is null"
130                                 utils.log("DEBUG", msg, isDebugEnabled)
131                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
132                         }
133                         execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
134                         utils.log("DEBUG","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled)
135
136                         //requestDetails.modelInfo.for AAI PUT servieInstanceData & SDNC assignTopology
137                         String modelInvariantUuid = ""
138                         String modelVersion = ""
139                         String modelUuid = ""
140                         String modelName = ""
141                         String serviceInstanceName = "" 
142                         //Generated in parent.for AAI PUT
143                         String serviceInstanceId = ""
144                         String serviceType = ""
145                         String serviceRole = ""
146                                         
147                         ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition")
148                         if (serviceDecomp != null)
149                         {
150                                 serviceType = serviceDecomp.getServiceType() ?: ""
151                                 utils.log("DEBUG", "serviceType:" + serviceType, isDebugEnabled)
152                                 serviceRole = serviceDecomp.getServiceRole() ?: ""
153                                 
154                                 ServiceInstance serviceInstance = serviceDecomp.getServiceInstance()
155                                 if (serviceInstance != null)
156                                 {
157                                         serviceInstanceId = serviceInstance.getInstanceId() ?: ""
158                                         serviceInstanceName = serviceInstance.getInstanceName() ?: ""
159                                         execution.setVariable("serviceInstanceId", serviceInstanceId)
160                                         execution.setVariable("serviceInstanceName", serviceInstanceName)
161                                 }
162                                 
163                                 ModelInfo modelInfo = serviceDecomp.getModelInfo()
164                                 if (modelInfo != null)
165                                 {
166                                         modelInvariantUuid = modelInfo.getModelInvariantUuid() ?: ""
167                                         modelVersion = modelInfo.getModelVersion() ?: ""
168                                         modelUuid = modelInfo.getModelUuid() ?: ""
169                                         modelName = modelInfo.getModelName() ?: ""
170                                 }
171                                 else 
172                                 {
173                                         msg = "Input serviceModelInfo is null"
174                                         utils.log("DEBUG", msg, isDebugEnabled)
175                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
176                                 }
177                         }
178                         else
179                         {
180                                 //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData & SDNC assignToplology
181                                 serviceInstanceName = execution.getVariable("serviceInstanceName") ?: ""
182                                 serviceInstanceId = execution.getVariable("serviceInstanceId") ?: ""
183                                 
184                                 String serviceModelInfo = execution.getVariable("serviceModelInfo")
185                                 if (isBlank(serviceModelInfo)) {
186                                         msg = "Input serviceModelInfo is null"
187                                         utils.log("DEBUG", msg, isDebugEnabled)
188                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
189                                 }                       
190                                 modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") ?: ""
191                                 modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") ?: ""
192                                 modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid") ?: ""
193                                 modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") ?: ""
194                                 //modelCustomizationUuid NA for SI
195         
196                         }
197                         
198                         execution.setVariable("serviceType", serviceType)
199                         execution.setVariable("serviceRole", serviceRole)
200                         execution.setVariable("serviceInstanceName", serviceInstanceName)
201
202                         execution.setVariable("modelInvariantUuid", modelInvariantUuid)
203                         execution.setVariable("modelVersion", modelVersion)
204                         execution.setVariable("modelUuid", modelUuid)
205                         execution.setVariable("modelName", modelName)
206                         
207                         //alacarte SIs are NOT sent to sdnc. exceptions are listed in config variable
208                         String svcTypes = execution.getVariable("URN_sdnc_si_svc_types") ?: ""
209                         utils.log("DEBUG", "SDNC SI serviceTypes:" + svcTypes, isDebugEnabled)
210                         List<String> svcList = Arrays.asList(svcTypes.split("\\s*,\\s*"));
211                         boolean isSdncService= false
212                         for (String listEntry : svcList){
213                                 if (listEntry.equalsIgnoreCase(serviceType)){
214                                         isSdncService = true
215                                         break;
216                                 }
217                         }
218                         
219                         //All Macros are sent to SDNC, TRANSPORT(Macro) is sent to SDNW
220                         //Alacartes are sent to SDNC if they are listed in config variable above
221                         execution.setVariable("sendToSDNC", true)
222                         if(execution.getVariable("sdncVersion").equals("1610")) //alacarte
223                         {
224                                 if(!isSdncService){ 
225                                         execution.setVariable("sendToSDNC", false)
226                                         //alacarte non-sdnc svcs must provide name (sdnc provides name for rest)
227                                         if (isBlank(execution.getVariable("serviceInstanceName" )))
228                                         {
229                                                 msg = "Input serviceInstanceName must be provided for alacarte"
230                                                 utils.log("DEBUG", msg, isDebugEnabled)
231                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
232                                         }
233                                 }
234                         }
235                         
236                         utils.log("DEBUG", "isSdncService: " + isSdncService, isDebugEnabled)
237                         utils.log("DEBUG", "Send To SDNC: " + execution.getVariable("sendToSDNC"), isDebugEnabled)
238                         utils.log("DEBUG", "Service Type: " + execution.getVariable("serviceType"), isDebugEnabled)
239                         
240                         //macro may provide name and alacarte-portm may provide name
241                         execution.setVariable("checkAAI", false)
242                         if (!isBlank(execution.getVariable("serviceInstanceName" )))
243                         {
244                                 execution.setVariable("checkAAI", true)
245                         }
246                         
247                         if (isBlank(serviceInstanceId)){
248                                 msg = "Input serviceInstanceId is null"
249                                 utils.log("DEBUG", msg, isDebugEnabled)
250                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
251                         }
252                         
253                         
254                         StringBuilder sbParams = new StringBuilder()
255                         Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
256                         if (paramsMap != null)
257                         {
258                                 sbParams.append("<service-input-parameters>")
259                                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
260                                         String paramsXml
261                                         String paramName = entry.getKey()
262                                         String paramValue = entry.getValue()
263                                         paramsXml =
264                                                         """     <param>
265                                                         <name>${paramName}</name>
266                                                         <value>${paramValue}</value>
267                                                         </param>
268                                                         """
269                                         sbParams.append(paramsXml)
270                                 }
271                                 sbParams.append("</service-input-parameters>")
272                         }
273                         String siParamsXml = sbParams.toString()
274                         if (siParamsXml == null)
275                                 siParamsXml = ""
276                         execution.setVariable("siParamsXml", siParamsXml)
277
278                         //AAI PUT
279                         String oStatus = execution.getVariable("initialStatus") ?: "Active"
280                         if ("TRANSPORT".equalsIgnoreCase(serviceType))
281                         {
282                                 oStatus = "Created"
283                         }
284
285                         String statusLine = isBlank(oStatus) ? "" : "<orchestration-status>${oStatus}</orchestration-status>"
286                         String serviceTypeLine = isBlank(serviceType) ? "" : "<service-type>${serviceType}</service-type>"
287                         String serviceRoleLine = isBlank(serviceRole) ? "" : "<service-role>${serviceRole}</service-role>"
288                                 
289                         //QUERY CATALOG DB AND GET WORKLOAD / ENVIRONMENT CONTEXT
290                         String environmentContext = ""
291                         String workloadContext =""
292                         
293                         try{
294                                  String json = cutils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid )
295                                  
296                                  utils.log("DEBUG", "JSON IS: "+json, isDebugEnabled)
297                                                                  
298                                  environmentContext = jsonUtil.getJsonValue(json, "serviceResources.environmentContext") ?: ""
299                                  workloadContext = jsonUtil.getJsonValue(json, "serviceResources.workloadContext") ?: ""
300                                  utils.log("DEBUG", "Env Context is: "+ environmentContext, isDebugEnabled)
301                                  utils.log("DEBUG", "Workload Context is: "+ workloadContext, isDebugEnabled)
302                         }catch(BpmnError e){
303                                 throw e
304                         } catch (Exception ex){
305                                 msg = "Exception in preProcessRequest " + ex.getMessage()
306                                 utils.log("DEBUG", msg, isDebugEnabled)
307                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
308                         }
309                         
310                         //Create AAI Payload
311                         AaiUtil aaiUriUtil = new AaiUtil(this)
312                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
313                         String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri)
314                         String serviceInstanceData =
315                                         """<service-instance xmlns=\"${namespace}\">
316                                         <service-instance-name>${serviceInstanceName}</service-instance-name>
317                                         ${serviceTypeLine}
318                                         ${serviceRoleLine}
319                                         ${statusLine}
320                                     <model-invariant-id>${modelInvariantUuid}</model-invariant-id>
321                                     <model-version-id>${modelUuid}</model-version-id>
322                                         <environment-context>${environmentContext}</environment-context>
323                                         <workload-context>${workloadContext}</workload-context>
324                                         </service-instance>""".trim()
325
326                         execution.setVariable("serviceInstanceData", serviceInstanceData)
327                         utils.logAudit(serviceInstanceData)
328                         utils.log("DEBUG", " 'payload' to create Service Instance in AAI - " + "\n" + serviceInstanceData, isDebugEnabled)
329                                 
330                 } catch (BpmnError e) {
331                         throw e;
332                 } catch (Exception ex){
333                         msg = "Exception in preProcessRequest " + ex.getMessage()
334                         utils.log("DEBUG", msg, isDebugEnabled)
335                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
336                 }
337                 utils.log("DEBUG"," ***** Exit preProcessRequest *****",  isDebugEnabled)
338         }
339
340         //TODO: Will be able to replace with call to GenericGetService
341         public void getAAICustomerById (DelegateExecution execution) {
342                 // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId}
343                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
344                 String msg = ""
345                 try {
346
347                         String globalCustomerId = execution.getVariable("globalSubscriberId") //VID to AAI name map
348                         utils.log("DEBUG"," ***** getAAICustomerById ***** globalCustomerId:" + globalCustomerId, isDebugEnabled)
349
350                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
351                         AaiUtil aaiUriUtil = new AaiUtil(this)
352                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
353                         if (isBlank(aai_endpoint) || isBlank(aai_uri))
354                         {
355                                 msg = "AAI URL is invalid. Endpoint:" + aai_endpoint + aai_uri
356                                 utils.log("DEBUG", msg, isDebugEnabled)
357                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
358                         }
359                         String getAAICustomerUrl = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8")
360
361                         utils.logAudit(getAAICustomerUrl)
362                         utils.log("DEBUG", "getAAICustomerById Url:" + getAAICustomerUrl, isDebugEnabled)
363                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getAAICustomerUrl)
364                         String returnCode = response.getStatusCode()
365                         String aaiResponseAsString = response.getResponseBodyAsString()
366
367                         msg = "getAAICustomerById ResponseCode:" + returnCode + " ResponseString:" + aaiResponseAsString
368                         utils.log("DEBUG",msg, isDebugEnabled)
369                         utils.logAudit(msg)
370
371                         if (returnCode=='200') {
372                                 // Customer found by ID. FLow to proceed.
373                                 utils.log("DEBUG",msg, isDebugEnabled)
374
375                                 //TODO Deferred
376                                 //we might verify that service-subscription with matching name exists
377                                 //and throw error if not. If not checked, we will get exception in subsequent step on Create call
378                                 //in 1610 we assume both customer & service subscription were pre-created
379
380                         } else {
381                                 if (returnCode=='404') {
382                                         msg = "GlobalCustomerId:" + globalCustomerId + " not found (404) in AAI"
383                                         utils.log("DEBUG", msg, isDebugEnabled)
384                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
385
386                                 } else {
387                                         if (aaiResponseAsString.contains("RESTFault")) {
388                                                 utils.log("ERROR", aaiResponseAsString)
389                                                 WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
390                                                 execution.setVariable("WorkflowException", workflowException)
391                                                 throw new BpmnError("MSOWorkflowException")
392
393                                         } else {
394                                                 // aai all errors
395                                                 msg = "Error in getAAICustomerById ResponseCode:" + returnCode
396                                                 utils.log("DEBUG", msg, isDebugEnabled)
397                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
398                                         }
399                                 }
400                         }
401
402                 } catch (BpmnError e) {
403                         throw e;
404                 } catch (Exception ex) {
405                         msg = "Exception in getAAICustomerById. " + ex.getMessage()
406                         utils.log("DEBUG", msg, isDebugEnabled)
407                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
408                 }
409                 utils.log("DEBUG"," *****Exit getAAICustomerById *****", isDebugEnabled)
410
411         }
412
413         public void postProcessAAIGET(DelegateExecution execution) {
414                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
415                 utils.log("DEBUG"," ***** postProcessAAIGET ***** ", isDebugEnabled)
416                 String msg = ""
417
418                 try {
419                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
420                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
421                         if(!succInAAI){
422                                 utils.log("DEBUG","Error getting Service-instance from AAI", + serviceInstanceName, isDebugEnabled)
423                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
424                                 utils.logAudit("workflowException: " + workflowException)
425                                 if(workflowException != null){
426                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
427                                 }
428                                 else
429                                 {
430                                         msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
431                                         utils.log("DEBUG", msg, isDebugEnabled)
432                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
433                                 }
434                         }
435                         else
436                         {
437                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
438                                 if(foundInAAI){
439                                         utils.log("DEBUG","Found Service-instance in AAI", isDebugEnabled)
440                                         msg = "ServiceInstance already exists in AAI:" + serviceInstanceName
441                                         utils.log("DEBUG", msg, isDebugEnabled)
442                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
443                                 }
444                         }
445                 } catch (BpmnError e) {
446                         throw e;
447                 } catch (Exception ex) {
448                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage()
449                         utils.log("DEBUG", msg, isDebugEnabled)
450                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
451                 }
452                 utils.log("DEBUG"," *** Exit postProcessAAIGET *** ", isDebugEnabled)
453         }
454
455         public void postProcessAAIPUT(DelegateExecution execution) {
456                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
457                 utils.log("DEBUG"," ***** postProcessAAIPUT ***** ", isDebugEnabled)
458                 String msg = ""
459                 try {
460                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
461                         boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator")
462                         if(!succInAAI){
463                                 utils.log("DEBUG","Error putting Service-instance in AAI", + serviceInstanceId, isDebugEnabled)
464                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
465                                 utils.logAudit("workflowException: " + workflowException)
466                                 if(workflowException != null){
467                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
468                                 }
469                         }
470                         else
471                         {
472                                 //start rollback set up
473                                 RollbackData rollbackData = new RollbackData()
474                                 def disableRollback = execution.getVariable("disableRollback")
475                                 rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
476                                 rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
477                                 rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId)
478                                 rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
479                                 rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
480                                 execution.setVariable("rollbackData", rollbackData)
481                         }
482
483                 } catch (BpmnError e) {
484                         throw e;
485                 } catch (Exception ex) {
486                         msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage()
487                         utils.log("DEBUG", msg, isDebugEnabled)
488                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
489                 }
490                 utils.log("DEBUG"," *** Exit postProcessAAIPUT *** ", isDebugEnabled)
491         }
492
493         public void preProcessSDNCAssignRequest(DelegateExecution execution) {
494                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
495                 String msg = ""
496                 utils.log("DEBUG"," ***** preProcessSDNCAssignRequest *****", isDebugEnabled)
497
498                 try {
499                         def serviceInstanceId = execution.getVariable("serviceInstanceId")
500                         def serviceInstanceName = execution.getVariable("serviceInstanceName")
501                         def callbackURL = execution.getVariable("sdncCallbackUrl")
502                         def requestId = execution.getVariable("msoRequestId")
503                         def serviceId = execution.getVariable("productFamilyId")
504                         def subscriptionServiceType = execution.getVariable("subscriptionServiceType")
505                         def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
506                         def msoAction = ""
507
508                         def modelInvariantUuid = execution.getVariable("modelInvariantUuid")
509                         def modelVersion = execution.getVariable("modelVersion")
510                         def modelUuid = execution.getVariable("modelUuid")
511                         def modelName = execution.getVariable("modelName")
512                         
513                         def sdncRequestId = UUID.randomUUID().toString()
514                         
515                         def siParamsXml = execution.getVariable("siParamsXml")
516                         
517                         // special URL for SDNW, msoAction helps set diff url in SDNCA
518                         if("TRANSPORT".equalsIgnoreCase(execution.getVariable("serviceType")))
519                         {
520                                 msoAction = "TRANSPORT"
521                         }
522                         
523                         String sdncAssignRequest =
524                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
525                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
526                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
527                                    <sdncadapter:RequestHeader>
528                                                         <sdncadapter:RequestId>${sdncRequestId}</sdncadapter:RequestId>
529                                                         <sdncadapter:SvcInstanceId>${serviceInstanceId}</sdncadapter:SvcInstanceId>
530                                                         <sdncadapter:SvcAction>assign</sdncadapter:SvcAction>
531                                                         <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
532                                                         <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
533                                                         <sdncadapter:MsoAction>${msoAction}</sdncadapter:MsoAction>
534                                         </sdncadapter:RequestHeader>
535                                 <sdncadapterworkflow:SDNCRequestData>
536                                         <request-information>
537                                                 <request-id>${requestId}</request-id>
538                                                 <source>MSO</source>
539                                                 <notification-url/>
540                                                 <order-number/>
541                                                 <order-version/>
542                                                 <request-action>CreateServiceInstance</request-action>
543                                         </request-information>
544                                         <service-information>
545                                                 <service-id>${serviceId}</service-id>
546                                                 <subscription-service-type>${subscriptionServiceType}</subscription-service-type>
547                                                 <onap-model-information>
548                                                  <model-invariant-uuid>${modelInvariantUuid}</model-invariant-uuid>
549                                                  <model-uuid>${modelUuid}</model-uuid>
550                                                  <model-version>${modelVersion}</model-version>
551                                                  <model-name>${modelName}</model-name>
552                                             </onap-model-information>
553                                                 <service-instance-id>${serviceInstanceId}</service-instance-id>
554                                                 <subscriber-name/>
555                                                 <global-customer-id>${globalSubscriberId}</global-customer-id>
556                                         </service-information>
557                                         <service-request-input>
558                                                 <service-instance-name>${serviceInstanceName}</service-instance-name>
559                                                 ${siParamsXml}
560                                         </service-request-input>
561                                 </sdncadapterworkflow:SDNCRequestData>
562                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
563
564                         utils.log("DEBUG","sdncAssignRequest:\n" + sdncAssignRequest, isDebugEnabled)
565                         sdncAssignRequest = utils.formatXml(sdncAssignRequest)
566                         execution.setVariable("sdncAssignRequest", sdncAssignRequest)
567                         utils.logAudit("sdncAssignRequest:  " + sdncAssignRequest)
568
569                         def sdncRequestId2 = UUID.randomUUID().toString()
570                         String sdncDelete = sdncAssignRequest.replace(">assign<", ">delete<").replace(">CreateServiceInstance<", ">DeleteServiceInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<")
571                         def sdncRequestId3 = UUID.randomUUID().toString()
572                         String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId2}<", ">${sdncRequestId3}<")
573                         def rollbackData = execution.getVariable("rollbackData")
574                         rollbackData.put("SERVICEINSTANCE", "sdncDeactivate", sdncDeactivate)
575                         rollbackData.put("SERVICEINSTANCE", "sdncDelete", sdncDelete)
576                         execution.setVariable("rollbackData", rollbackData)
577                         
578                         utils.log("DEBUG","rollbackData:\n" + rollbackData.toString(), isDebugEnabled)
579
580                 } catch (BpmnError e) {
581                         throw e;
582                 } catch(Exception ex) {
583                         msg = "Exception in preProcessSDNCAssignRequest. " + ex.getMessage()
584                         utils.log("DEBUG", msg, isDebugEnabled)
585                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
586                 }
587                 utils.log("DEBUG"," *****Exit preProcessSDNCAssignRequest *****", isDebugEnabled)
588         }
589         
590         public void postProcessSDNCAssign (DelegateExecution execution) {
591                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
592                 utils.log("DEBUG"," ***** postProcessSDNCAssign ***** ", isDebugEnabled)
593                 try {
594                         WorkflowException workflowException = execution.getVariable("WorkflowException")
595                         utils.logAudit("workflowException: " + workflowException)
596
597                         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
598
599                         String response = execution.getVariable("sdncAdapterResponse")
600                         utils.logAudit("SDNCResponse: " + response)
601
602                         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
603                         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
604
605                         if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
606                                 utils.log("DEBUG","Good response from SDNC Adapter for service-instance  topology assign: \n" + response, isDebugEnabled)
607
608                                 def rollbackData = execution.getVariable("rollbackData")
609                                 rollbackData.put("SERVICEINSTANCE", "rollbackSDNC", "true")
610                                 execution.setVariable("rollbackData", rollbackData)
611
612                         }else{
613                                 utils.log("DEBUG","Bad Response from SDNC Adapter for service-instance assign", isDebugEnabled)
614                                 throw new BpmnError("MSOWorkflowException")
615                         }
616
617                 } catch (BpmnError e) {
618                         throw e;
619                 } catch(Exception ex) {
620                         msg = "Exception in postProcessSDNCAssign. " + ex.getMessage()
621                         utils.log("DEBUG", msg, isDebugEnabled)
622                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
623                 }
624                 utils.log("DEBUG"," *** Exit postProcessSDNCAssign *** ", isDebugEnabled)
625         }
626         
627         public void postProcessAAIGET2(DelegateExecution execution) {
628                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
629                 utils.log("DEBUG"," ***** postProcessAAIGET2 ***** ", isDebugEnabled)
630                 String msg = ""
631
632                 try {
633                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
634                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
635                         if(!succInAAI){
636                                 utils.log("DEBUG","Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName, isDebugEnabled)
637                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
638                                 utils.logAudit("workflowException: " + workflowException)
639                                 if(workflowException != null){
640                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
641                                 }
642                                 else
643                                 {
644                                         msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI
645                                         utils.log("DEBUG", msg, isDebugEnabled)
646                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
647                                 }
648                         }
649                         else
650                         {
651                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
652                                 if(foundInAAI){
653                                         String aaiService = execution.getVariable("GENGS_service")
654                                         if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) {
655                                                 execution.setVariable("serviceInstanceName",  utils.getNodeText1(aaiService, "service-instance-name"))
656                                                 utils.log("DEBUG","Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName"), isDebugEnabled)
657                                         }
658                                 }
659                         }
660                 } catch (BpmnError e) {
661                         throw e;
662                 } catch (Exception ex) {
663                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage()
664                         utils.log("DEBUG", msg, isDebugEnabled)
665                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
666                 }
667                 utils.log("DEBUG"," *** Exit postProcessAAIGET2 *** ", isDebugEnabled)
668         }
669
670         public void preProcessRollback (DelegateExecution execution) {
671                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
672                 utils.log("DEBUG"," ***** preProcessRollback ***** ", isDebugEnabled)
673                 try {
674                         
675                         Object workflowException = execution.getVariable("WorkflowException");
676
677                         if (workflowException instanceof WorkflowException) {
678                                 utils.log("DEBUG", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled)
679                                 execution.setVariable("prevWorkflowException", workflowException);
680                                 //execution.setVariable("WorkflowException", null);
681                         }
682                 } catch (BpmnError e) {
683                         utils.log("DEBUG", "BPMN Error during preProcessRollback", isDebugEnabled)
684                 } catch(Exception ex) {
685                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
686                         utils.log("DEBUG", msg, isDebugEnabled)
687                 }
688                 utils.log("DEBUG"," *** Exit preProcessRollback *** ", isDebugEnabled)
689         }
690
691         public void postProcessRollback (DelegateExecution execution) {
692                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
693                 utils.log("DEBUG"," ***** postProcessRollback ***** ", isDebugEnabled)
694                 String msg = ""
695                 try {
696                         Object workflowException = execution.getVariable("prevWorkflowException");
697                         if (workflowException instanceof WorkflowException) {
698                                 utils.log("DEBUG", "Setting prevException to WorkflowException: ", isDebugEnabled)
699                                 execution.setVariable("WorkflowException", workflowException);
700                         }
701                         execution.setVariable("rollbackData", null)
702                 } catch (BpmnError b) {
703                         utils.log("DEBUG", "BPMN Error during postProcessRollback", isDebugEnabled)
704                         throw b;
705                 } catch(Exception ex) {
706                         msg = "Exception in postProcessRollback. " + ex.getMessage()
707                         utils.log("DEBUG", msg, isDebugEnabled)
708                 }
709                 utils.log("DEBUG"," *** Exit postProcessRollback *** ", isDebugEnabled)
710         }
711         
712         public void createProject(DelegateExecution execution) {
713                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
714                 utils.log("DEBUG", " ***** createProject ***** ", isDebugEnabled)
715
716                 String bpmnRequest = execution.getVariable("requestJson")       
717                 String projectName = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.project.projectName")           
718                 String serviceInstance = execution.getVariable("serviceInstanceId")
719                 
720                 utils.log("DEBUG", "BPMN REQUEST IS: "+ bpmnRequest, isDebugEnabled)
721                 utils.log("DEBUG","PROJECT NAME: " + projectName, isDebugEnabled)
722                 utils.log("DEBUG","Service Instance: " + serviceInstance, isDebugEnabled)
723                         
724                 if(projectName == null||projectName.equals("")){
725                         utils.log("DEBUG", "Project Name was not found in input. Skipping task...", isDebugEnabled)
726                 }else{
727                         try{
728                                 AAICreateResources aaiCR = new AAICreateResources()
729                                 aaiCR.createAAIProject(projectName, serviceInstance)
730                         }catch(Exception ex){
731                                 String msg = "Exception in createProject. " + ex.getMessage();
732                                 utils.log("DEBUG", msg, isDebugEnabled)
733                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
734                         }
735                 }       
736                 utils.log("DEBUG"," *** Exit createProject *** ", isDebugEnabled)
737         }
738         
739         public void createOwningEntity(DelegateExecution execution) {
740                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
741                 utils.log("DEBUG", " ***** createOwningEntity ***** ", isDebugEnabled)
742                 String msg = "";
743                 String bpmnRequest = execution.getVariable("requestJson")       
744                 String owningEntityId = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.owningEntity.owningEntityId")                
745                 String owningEntityName = jsonUtil.getJsonValue(bpmnRequest,"requestDetails.owningEntity.owningEntityName");
746                 String serviceInstance = execution.getVariable("serviceInstanceId")
747                         
748                 utils.log("DEBUG","owningEntity: " + owningEntityId, isDebugEnabled)
749                 utils.log("DEBUG", "OwningEntityName: "+ owningEntityName, isDebugEnabled)
750                 utils.log("DEBUG","Service Instance: " + serviceInstance, isDebugEnabled)
751                 
752                 try{
753                         AAICreateResources aaiCR = new AAICreateResources()
754                         if(owningEntityId==null||owningEntityId.equals("")){
755                                 msg = "Exception in createOwningEntity. OwningEntityId is null in input.";      
756                                 throw new IllegalStateException();
757                         }else{
758                                 if(aaiCR.existsOwningEntity(owningEntityId)){
759                                         aaiCR.connectOwningEntityandServiceInstance(owningEntityId,serviceInstance)
760                                 }else{
761                                         if(owningEntityName==null||owningEntityName.equals("")){
762                                                 msg = "Exception in createOwningEntity. Can't create an owningEntity without an owningEntityName in input.";
763                                                 throw new IllegalStateException();
764                                         }else{
765                                                 aaiCR.createAAIOwningEntity(owningEntityId, owningEntityName, serviceInstance)
766                                         }
767                                 }
768                         }
769                 }catch(Exception ex){
770                         utils.log("DEBUG", msg, isDebugEnabled)
771                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
772                 }
773                 utils.log("DEBUG"," *** Exit createOwningEntity *** ", isDebugEnabled)
774         }
775         
776         // *******************************
777         //     Build Error Section
778         // *******************************
779
780         public void processJavaException(DelegateExecution execution){
781                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
782                 
783                 try{
784                         utils.log("DEBUG", "Caught a Java Exception in DoCreateServiceInstance", isDebugEnabled)
785                         utils.log("DEBUG", "Started processJavaException Method", isDebugEnabled)
786                         utils.log("DEBUG", "Variables List: " + execution.getVariables(), isDebugEnabled)
787                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception in DoCreateServiceInstance")  // Adding this line temporarily until this flows error handling gets updated
788                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception in DoCreateServiceInstance")
789                         
790                 }catch(Exception e){
791                         utils.log("DEBUG", "Caught Exception during processJavaException Method: " + e, isDebugEnabled)
792                         execution.setVariable("UnexpectedError", "Exception in processJavaException")  // Adding this line temporarily until this flows error handling gets updated
793                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method")
794                 }
795                 utils.log("DEBUG", "Completed processJavaException Method in DoCreateServiceInstance", isDebugEnabled)
796         }
797
798 }