Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / 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         //TODO: Will be able to replace with call to GenericGetService
333         public void getAAICustomerById (DelegateExecution execution) {
334                 // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId}
335                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
336                 String msg = ""
337                 try {
338
339                         String globalCustomerId = execution.getVariable("globalSubscriberId") //VID to AAI name map
340                         msoLogger.debug(" ***** getAAICustomerById ***** globalCustomerId:" + globalCustomerId)
341
342                         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
343                         AaiUtil aaiUriUtil = new AaiUtil(this)
344                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
345                         if (isBlank(aai_endpoint) || isBlank(aai_uri))
346                         {
347                                 msg = "AAI URL is invalid. Endpoint:" + aai_endpoint + aai_uri
348                                 msoLogger.debug(msg)
349                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
350                         }
351                         String getAAICustomerUrl = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8")
352
353                         msoLogger.debug("getAAICustomerById Url:" + getAAICustomerUrl)
354                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getAAICustomerUrl)
355                         String returnCode = response.getStatusCode()
356                         String aaiResponseAsString = response.getResponseBodyAsString()
357
358                         msg = "getAAICustomerById ResponseCode:" + returnCode + " ResponseString:" + aaiResponseAsString
359                         msoLogger.debug(msg)
360
361                         if (returnCode=='200') {
362                                 // Customer found by ID. FLow to proceed.
363                                 msoLogger.debug(msg)
364
365                                 //TODO Deferred
366                                 //we might verify that service-subscription with matching name exists
367                                 //and throw error if not. If not checked, we will get exception in subsequent step on Create call
368                                 //in 1610 we assume both customer & service subscription were pre-created
369
370                         } else {
371                                 if (returnCode=='404') {
372                                         msg = "GlobalCustomerId:" + globalCustomerId + " not found (404) in AAI"
373                                         msoLogger.debug(msg)
374                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
375
376                                 } else {
377                                         if (aaiResponseAsString.contains("RESTFault")) {
378                                                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, aaiResponseAsString, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
379                                                 WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution)
380                                                 execution.setVariable("WorkflowException", workflowException)
381                                                 throw new BpmnError("MSOWorkflowException")
382
383                                         } else {
384                                                 // aai all errors
385                                                 msg = "Error in getAAICustomerById ResponseCode:" + returnCode
386                                                 msoLogger.debug(msg)
387                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
388                                         }
389                                 }
390                         }
391
392                 } catch (BpmnError e) {
393                         throw e;
394                 } catch (Exception ex) {
395                         msg = "Exception in getAAICustomerById. " + ex.getMessage()
396                         msoLogger.debug(msg)
397                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
398                 }
399                 msoLogger.trace("Exit getAAICustomerById")
400
401         }
402
403         public void postProcessAAIGET(DelegateExecution execution) {
404                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
405                 msoLogger.trace("postProcessAAIGET")
406                 String msg = ""
407
408                 try {
409                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
410                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
411                         if(!succInAAI){
412                                 msoLogger.debug("Error getting Service-instance from AAI", + serviceInstanceName)
413                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
414                                 if(workflowException != null){
415                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
416                                 }
417                                 else
418                                 {
419                                         msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
420                                         msoLogger.debug(msg)
421                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
422                                 }
423                         }
424                         else
425                         {
426                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
427                                 if(foundInAAI){
428                                         msoLogger.debug("Found Service-instance in AAI")
429                                         msg = "ServiceInstance already exists in AAI:" + serviceInstanceName
430                                         msoLogger.debug(msg)
431                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
432                                 }
433                         }
434                 } catch (BpmnError e) {
435                         throw e;
436                 } catch (Exception ex) {
437                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage()
438                         msoLogger.debug(msg)
439                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
440                 }
441                 msoLogger.trace("Exit postProcessAAIGET")
442         }
443
444         public void postProcessAAIPUT(DelegateExecution execution) {
445                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
446                 msoLogger.trace("postProcessAAIPUT")
447                 String msg = ""
448                 try {
449                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
450                         boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator")
451                         if(!succInAAI){
452                                 msoLogger.debug("Error putting Service-instance in AAI", + serviceInstanceId)
453                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
454                                 msoLogger.debug("workflowException: " + workflowException)
455                                 if(workflowException != null){
456                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
457                                 }
458                         }
459                         else
460                         {
461                                 //start rollback set up
462                                 RollbackData rollbackData = new RollbackData()
463                                 def disableRollback = execution.getVariable("disableRollback")
464                                 rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString())
465                                 rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true")
466                                 rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId)
467                                 rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType"))
468                                 rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId"))
469                                 execution.setVariable("rollbackData", rollbackData)
470                         }
471
472                 } catch (BpmnError e) {
473                         throw e;
474                 } catch (Exception ex) {
475                         msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage()
476                         msoLogger.debug(msg)
477                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
478                 }
479                 msoLogger.trace("Exit postProcessAAIPUT")
480         }
481
482         public void preProcessSDNCAssignRequest(DelegateExecution execution) {
483                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
484                 String msg = ""
485                 msoLogger.trace("preProcessSDNCAssignRequest")
486
487                 try {
488                         def serviceInstanceId = execution.getVariable("serviceInstanceId")
489                         def serviceInstanceName = execution.getVariable("serviceInstanceName")
490                         def callbackURL = execution.getVariable("sdncCallbackUrl")
491                         def requestId = execution.getVariable("msoRequestId")
492                         def serviceId = execution.getVariable("productFamilyId")
493                         def subscriptionServiceType = execution.getVariable("subscriptionServiceType")
494                         def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
495                         def msoAction = ""
496
497                         def modelInvariantUuid = execution.getVariable("modelInvariantUuid")
498                         def modelVersion = execution.getVariable("modelVersion")
499                         def modelUuid = execution.getVariable("modelUuid")
500                         def modelName = execution.getVariable("modelName")
501                         
502                         def sdncRequestId = UUID.randomUUID().toString()
503                         
504                         def siParamsXml = execution.getVariable("siParamsXml")
505                         
506                         // special URL for SDNW, msoAction helps set diff url in SDNCA
507                         if("TRANSPORT".equalsIgnoreCase(execution.getVariable("serviceType")))
508                         {
509                                 msoAction = "TRANSPORT"
510                         }
511                         
512                         String sdncAssignRequest =
513                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1"
514                                                                                                         xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"
515                                                                                                         xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1">
516                                    <sdncadapter:RequestHeader>
517                                                         <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId>
518                                                         <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
519                                                         <sdncadapter:SvcAction>assign</sdncadapter:SvcAction>
520                                                         <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
521                                                         <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl>
522                                                         <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction>
523                                         </sdncadapter:RequestHeader>
524                                 <sdncadapterworkflow:SDNCRequestData>
525                                         <request-information>
526                                                 <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
527                                                 <source>MSO</source>
528                                                 <notification-url/>
529                                                 <order-number/>
530                                                 <order-version/>
531                                                 <request-action>CreateServiceInstance</request-action>
532                                         </request-information>
533                                         <service-information>
534                                                 <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id>
535                                                 <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type>
536                                                 <onap-model-information>
537                                                  <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid>
538                                                  <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid>
539                                                  <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version>
540                                                  <model-name>${MsoUtils.xmlEscape(modelName)}</model-name>
541                                             </onap-model-information>
542                                                 <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
543                                                 <subscriber-name/>
544                                                 <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id>
545                                         </service-information>
546                                         <service-request-input>
547                                                 <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name>
548                                                 ${siParamsXml}
549                                         </service-request-input>
550                                 </sdncadapterworkflow:SDNCRequestData>
551                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
552
553                         msoLogger.debug("sdncAssignRequest:\n" + sdncAssignRequest)
554                         sdncAssignRequest = utils.formatXml(sdncAssignRequest)
555                         execution.setVariable("sdncAssignRequest", sdncAssignRequest)
556                         msoLogger.debug("sdncAssignRequest:  " + sdncAssignRequest)
557
558                         def sdncRequestId2 = UUID.randomUUID().toString()
559                         String sdncDelete = sdncAssignRequest.replace(">assign<", ">delete<").replace(">CreateServiceInstance<", ">DeleteServiceInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<")
560                         def sdncRequestId3 = UUID.randomUUID().toString()
561                         String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId2}<", ">${sdncRequestId3}<")
562                         def rollbackData = execution.getVariable("rollbackData")
563                         rollbackData.put("SERVICEINSTANCE", "sdncDeactivate", sdncDeactivate)
564                         rollbackData.put("SERVICEINSTANCE", "sdncDelete", sdncDelete)
565                         execution.setVariable("rollbackData", rollbackData)
566                         
567                         msoLogger.debug("rollbackData:\n" + rollbackData.toString())
568
569                 } catch (BpmnError e) {
570                         throw e;
571                 } catch(Exception ex) {
572                         msg = "Exception in preProcessSDNCAssignRequest. " + ex.getMessage()
573                         msoLogger.debug(msg)
574                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
575                 }
576                 msoLogger.trace("Exit preProcessSDNCAssignRequest")
577         }
578         
579         public void postProcessSDNCAssign (DelegateExecution execution) {
580                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
581                 msoLogger.trace("postProcessSDNCAssign")
582                 try {
583                         WorkflowException workflowException = execution.getVariable("WorkflowException")
584                         msoLogger.debug("workflowException: " + workflowException)
585
586                         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
587
588                         String response = execution.getVariable("sdncAdapterResponse")
589                         msoLogger.debug("SDNCResponse: " + response)
590
591                         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
592                         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
593
594                         if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
595                                 msoLogger.debug("Good response from SDNC Adapter for service-instance  topology assign: \n" + response)
596
597                                 def rollbackData = execution.getVariable("rollbackData")
598                                 rollbackData.put("SERVICEINSTANCE", "rollbackSDNC", "true")
599                                 execution.setVariable("rollbackData", rollbackData)
600
601                         }else{
602                                 msoLogger.debug("Bad Response from SDNC Adapter for service-instance assign")
603                                 throw new BpmnError("MSOWorkflowException")
604                         }
605
606                 } catch (BpmnError e) {
607                         throw e;
608                 } catch(Exception ex) {
609                         msg = "Exception in postProcessSDNCAssign. " + ex.getMessage()
610                         msoLogger.debug(msg)
611                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
612                 }
613                 msoLogger.trace("Exit postProcessSDNCAssign")
614         }
615         
616         public void postProcessAAIGET2(DelegateExecution execution) {
617                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
618                 msoLogger.trace("postProcessAAIGET2")
619                 String msg = ""
620
621                 try {
622                         String serviceInstanceName = execution.getVariable("serviceInstanceName")
623                         boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
624                         if(!succInAAI){
625                                 msoLogger.debug("Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName)
626                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
627                                 msoLogger.debug("workflowException: " + workflowException)
628                                 if(workflowException != null){
629                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
630                                 }
631                                 else
632                                 {
633                                         msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI
634                                         msoLogger.debug(msg)
635                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
636                                 }
637                         }
638                         else
639                         {
640                                 boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
641                                 if(foundInAAI){
642                                         String aaiService = execution.getVariable("GENGS_service")
643                                         if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) {
644                                                 execution.setVariable("serviceInstanceName",  utils.getNodeText(aaiService, "service-instance-name"))
645                                                 msoLogger.debug("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName"))
646                                         }
647                                 }
648                         }
649                 } catch (BpmnError e) {
650                         throw e;
651                 } catch (Exception ex) {
652                         msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage()
653                         msoLogger.debug(msg)
654                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
655                 }
656                 msoLogger.trace("Exit postProcessAAIGET2")
657         }
658
659         public void preProcessRollback (DelegateExecution execution) {
660                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
661                 msoLogger.trace("preProcessRollback")
662                 try {
663                         
664                         Object workflowException = execution.getVariable("WorkflowException");
665
666                         if (workflowException instanceof WorkflowException) {
667                                 msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage())
668                                 execution.setVariable("prevWorkflowException", workflowException);
669                                 //execution.setVariable("WorkflowException", null);
670                         }
671                 } catch (BpmnError e) {
672                         msoLogger.debug("BPMN Error during preProcessRollback")
673                 } catch(Exception ex) {
674                         String msg = "Exception in preProcessRollback. " + ex.getMessage()
675                         msoLogger.debug(msg)
676                 }
677                 msoLogger.trace("Exit preProcessRollback")
678         }
679
680         public void postProcessRollback (DelegateExecution execution) {
681                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
682                 msoLogger.trace("postProcessRollback")
683                 String msg = ""
684                 try {
685                         Object workflowException = execution.getVariable("prevWorkflowException");
686                         if (workflowException instanceof WorkflowException) {
687                                 msoLogger.debug("Setting prevException to WorkflowException: ")
688                                 execution.setVariable("WorkflowException", workflowException);
689                         }
690                         execution.setVariable("rollbackData", null)
691                 } catch (BpmnError b) {
692                         msoLogger.debug("BPMN Error during postProcessRollback")
693                         throw b;
694                 } catch(Exception ex) {
695                         msg = "Exception in postProcessRollback. " + ex.getMessage()
696                         msoLogger.debug(msg)
697                 }
698                 msoLogger.trace("Exit postProcessRollback")
699         }
700         
701         public void createProject(DelegateExecution execution) {
702                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
703                 msoLogger.trace("createProject")
704
705                 String bpmnRequest = execution.getVariable("requestJson")       
706                 String projectName = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.project.projectName")           
707                 String serviceInstance = execution.getVariable("serviceInstanceId")
708                 
709                 msoLogger.debug("BPMN REQUEST IS: "+ bpmnRequest)
710                 msoLogger.debug("PROJECT NAME: " + projectName)
711                 msoLogger.debug("Service Instance: " + serviceInstance)
712                         
713                 if(projectName == null||projectName.equals("")){
714                         msoLogger.debug("Project Name was not found in input. Skipping task...")
715                 }else{
716                         try{
717                                 AAICreateResources aaiCR = new AAICreateResources()
718                                 aaiCR.createAAIProject(projectName, serviceInstance)
719                         }catch(Exception ex){
720                                 String msg = "Exception in createProject. " + ex.getMessage();
721                                 msoLogger.debug(msg)
722                                 msoLogger.error(ex);
723                                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
724                         }
725                 }       
726                 msoLogger.trace("Exit createProject")
727         }
728         
729         public void createOwningEntity(DelegateExecution execution) {
730                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
731                 msoLogger.trace("createOwningEntity")
732                 String msg = "";
733                 String bpmnRequest = execution.getVariable("requestJson")       
734                 String owningEntityId = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.owningEntity.owningEntityId")                
735                 String owningEntityName = jsonUtil.getJsonValue(bpmnRequest,"requestDetails.owningEntity.owningEntityName");
736                 String serviceInstance = execution.getVariable("serviceInstanceId")
737                         
738                 msoLogger.debug("owningEntity: " + owningEntityId)
739                 msoLogger.debug("OwningEntityName: "+ owningEntityName)
740                 msoLogger.debug("Service Instance: " + serviceInstance)
741                 
742                 try{
743                         AAICreateResources aaiCR = new AAICreateResources()
744                         if(owningEntityId==null||owningEntityId.equals("")){
745                                 msg = "Exception in createOwningEntity. OwningEntityId is null in input.";      
746                                 throw new IllegalStateException();
747                         }else{
748                                 if(aaiCR.existsOwningEntity(owningEntityId)){
749                                         aaiCR.connectOwningEntityandServiceInstance(owningEntityId,serviceInstance)
750                                 }else{
751                                         if(owningEntityName==null||owningEntityName.equals("")){
752                                                 msg = "Exception in createOwningEntity. Can't create an owningEntity without an owningEntityName in input.";
753                                                 throw new IllegalStateException();
754                                         }else{
755                                                 Optional<OwningEntity> owningEntity = aaiCR.getOwningEntityNames(owningEntityName);
756                                                 if(owningEntity.isPresent()){
757                                                         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).";
758                                                         throw new IllegalStateException();
759                                                 } else {
760                                                         aaiCR.createAAIOwningEntity(owningEntityId, owningEntityName, serviceInstance)
761                                                 }
762                                         }
763                                 }
764                         }
765                 }catch(Exception ex){
766                         msoLogger.debug(msg)
767                         msoLogger.error(ex);
768                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
769                 }
770                 msoLogger.trace("Exit createOwningEntity")
771         }
772         
773         // *******************************
774         //     Build Error Section
775         // *******************************
776
777         public void processJavaException(DelegateExecution execution){
778                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
779                 
780                 try{
781                         msoLogger.debug("Caught a Java Exception in DoCreateServiceInstance")
782                         msoLogger.debug("Started processJavaException Method")
783                         msoLogger.debug("Variables List: " + execution.getVariables())
784                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception in DoCreateServiceInstance")  // Adding this line temporarily until this flows error handling gets updated
785                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception in DoCreateServiceInstance")
786                         
787                 }catch(Exception e){
788                         msoLogger.debug("Caught Exception during processJavaException Method: " + e)
789                         execution.setVariable("UnexpectedError", "Exception in processJavaException")  // Adding this line temporarily until this flows error handling gets updated
790                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method")
791                 }
792                 msoLogger.trace("Completed processJavaException Method in DoCreateServiceInstance")
793         }
794
795 }