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