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