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