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