Merge "error message formatter now handles percent"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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 package org.onap.so.bpmn.infrastructure.scripts
23
24
25 import groovy.json.JsonOutput
26 import groovy.json.JsonSlurper
27 import org.apache.commons.lang3.StringUtils
28 import org.apache.commons.lang3.tuple.ImmutablePair
29 import org.camunda.bpm.engine.delegate.BpmnError
30 import org.camunda.bpm.engine.delegate.DelegateExecution
31 import org.json.JSONArray
32 import org.json.JSONObject
33 import org.onap.aai.domain.yang.RelatedToProperty
34 import org.onap.aai.domain.yang.Relationship
35 import org.onap.aai.domain.yang.RelationshipData
36 import org.onap.aai.domain.yang.ServiceInstance
37 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
38 import org.onap.so.bpmn.common.scripts.ExceptionUtil
39 import org.onap.so.bpmn.common.scripts.MsoUtils
40 import org.onap.so.bpmn.core.UrnPropertiesReader
41 import org.onap.so.bpmn.core.domain.GroupResource
42 import org.onap.so.bpmn.core.domain.Resource
43 import org.onap.so.bpmn.core.domain.ResourceType
44 import org.onap.so.bpmn.core.domain.ServiceDecomposition
45 import org.onap.so.bpmn.core.domain.VnfResource
46 import org.onap.so.bpmn.core.domain.VnfcResource
47 import org.onap.so.bpmn.core.json.JsonUtils
48 import org.onap.so.client.HttpClient
49 import org.onap.so.client.HttpClientFactory
50 import org.onap.so.client.aai.AAIObjectType
51 import org.onap.so.client.aai.AAIResourcesClient
52 import org.onap.so.client.aai.entities.AAIResultWrapper
53 import org.onap.so.client.aai.entities.uri.AAIResourceUri
54 import org.onap.so.client.aai.entities.uri.AAIUriFactory
55 import org.slf4j.Logger
56 import org.slf4j.LoggerFactory
57 import org.onap.logging.filter.base.ONAPComponents;
58 import org.springframework.web.util.UriUtils
59
60 import javax.ws.rs.NotFoundException
61 import javax.ws.rs.core.MediaType
62 import javax.ws.rs.core.Response
63
64 import static org.apache.commons.lang3.StringUtils.isBlank
65
66 /**
67  * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process.
68  *
69  * Inputs:
70  * @param - msoRequestId
71  * @param - globalSubscriberId - O
72  * @param - subscriptionServiceType - O
73  * @param - serviceInstanceId
74  * @param - serviceInstanceName - O
75  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
76  * @param - sdncVersion
77  * @param - failNotFound - TODO
78  * @param - serviceInputParams - TODO
79  *
80  * @param - delResourceList
81  * @param - serviceRelationShip
82  *
83  * Outputs:
84  * @param - WorkflowException
85  *
86  * Rollback - Deferred
87  */
88 public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
89
90         String Prefix="DDEESI_"
91     ExceptionUtil exceptionUtil = new ExceptionUtil()
92     JsonUtils jsonUtil = new JsonUtils()
93     private static final Logger logger = LoggerFactory.getLogger( DoDeleteE2EServiceInstance.class)
94
95
96     public void preProcessRequest (DelegateExecution execution) {
97         logger.debug(" ***** preProcessRequest *****")
98         String msg = ""
99
100         try {
101             String requestId = execution.getVariable("msoRequestId")
102             execution.setVariable("prefix",Prefix)
103
104             //Inputs
105             //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
106             String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
107             if (globalSubscriberId == null)
108             {
109                 execution.setVariable("globalSubscriberId", "")
110             }
111
112             //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
113             String serviceType = execution.getVariable("serviceType")
114             if (serviceType == null)
115             {
116                 execution.setVariable("serviceType", "")
117             }
118
119             //Generated in parent for AAI PUT
120             String serviceInstanceId = execution.getVariable("serviceInstanceId")
121             if (isBlank(serviceInstanceId)){
122                 msg = "Input serviceInstanceId is null"
123                 logger.info(msg)
124                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
125             }
126
127             String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback', execution)
128             if (isBlank(sdncCallbackUrl)) {
129                 msg = "URN_mso_workflow_sdncadapter_callback is null"
130                 logger.info(msg)
131                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
132             }
133             execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
134             logger.info("SDNC Callback URL: " + sdncCallbackUrl)
135
136             StringBuilder sbParams = new StringBuilder()
137             Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
138
139             if (paramsMap != null) {
140                 sbParams.append("<service-input-parameters>")
141                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
142                     String paramsXml
143                     String paramName = entry.getKey()
144                     String paramValue = entry.getValue()
145                     paramsXml =
146                             """ <param>
147                                                         <name>${MsoUtils.xmlEscape(paramName)}</name>
148                                                         <value>${MsoUtils.xmlEscape(paramValue)}</value>
149                                                         </param>
150                                                         """
151                     sbParams.append(paramsXml)
152                 }
153                 sbParams.append("</service-input-parameters>")
154             }
155             String siParamsXml = sbParams.toString()
156             if (siParamsXml == null)
157                 siParamsXml = ""
158             execution.setVariable("siParamsXml", siParamsXml)
159
160         } catch (BpmnError e) {
161             throw e
162         } catch (Exception ex){
163             msg = "Exception in preProcessRequest " + ex.getMessage()
164             logger.error(msg)
165             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
166         }
167         logger.debug("***** Exit preProcessRequest *****")
168     }
169
170     public void postProcessAAIGET(DelegateExecution execution) {
171         logger.debug(" ***** postProcessAAIGET ***** ")
172         String msg = ""
173
174         try {
175             String serviceInstanceId = execution.getVariable('serviceInstanceId')
176             String globalSubscriberId = execution.getVariable('globalSubscriberId')
177             String serviceType = execution.getVariable('serviceType')
178             AAIResourcesClient resourceClient = new AAIResourcesClient()
179             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId)
180             if (!resourceClient.exists(serviceInstanceUri)) {
181                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
182             }
183             AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class)
184             Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
185             // found in AAI
186             if (si.isPresent() && StringUtils.isNotEmpty(si.get().getServiceInstanceName())) {
187                 logger.debug("Found Service-instance in AAI")
188                 execution.setVariable("serviceInstanceName", si.get().getServiceInstanceName())
189                 // get model invariant id
190                 // Get Template uuid and version
191                 if ((null != si.get().getModelInvariantId()) && (null != si.get().getModelVersionId())) {
192                     logger.debug("SI Data model-invariant-id and model-version-id exist")
193                     // Set Original Template info
194                     execution.setVariable("model-invariant-id-original", si.get().getModelInvariantId())
195                     execution.setVariable("model-version-id-original", si.get().getModelVersionId())
196                 }
197                 if ((null != si.get().getRelationshipList()) && (null != si.get().getRelationshipList().getRelationship())) {
198                     logger.debug("SI Data relationship-list exists")
199                     List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
200                     JSONArray jArray = new JSONArray()
201                     for (Relationship relationship : relationshipList) {
202                         def jObj = getRelationShipData(relationship)
203                         jArray.put(jObj)
204                     }
205                     execution.setVariable("serviceRelationShip", jArray.toString())
206                 }
207             } else {
208                 msg = "Service-instance: " + serviceInstanceId + " NOT found in AAI."
209                 logger.error(msg)
210                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
211             }
212         } catch (BpmnError e) {
213             throw e
214         } catch (NotFoundException e) {
215             logger.debug("Service Instance does not exist AAI")
216             exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service Instance was not found in aai")
217         } catch (Exception ex) {
218             msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage()
219             logger.debug(msg)
220             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
221         }
222         logger.debug(" *** Exit postProcessAAIGET *** ")
223     }
224
225     private JSONObject getRelationShipData(Relationship relationship) {
226         JSONObject jObj = new JSONObject()
227         def rt = relationship.getRelatedTo()
228         def rl = relationship.getRelatedLink()
229         logger.debug("ServiceInstance Related NS/Configuration :" + rl)
230         List<RelationshipData> rl_datas = relationship.getRelationshipData()
231         for (RelationshipData rl_data : rl_datas) {
232             def eKey = rl_data.getRelationshipKey()
233             def eValue = rl_data.getRelationshipValue()
234             if ((rt.equals("service-instance") && eKey.equals("service-instance.service-instance-id"))
235                     //for overlay/underlay
236                     || (rt.equals("configuration") && eKey.equals("configuration.configuration-id")
237             )) {
238                 jObj.put("resourceInstanceId", eValue)
239             }
240             else if (rt.equals("allotted-resource") && eKey.equals("allotted-resource.id")){
241                 jObj.put("resourceInstanceId", eValue)
242             }
243             // for sp-partner and others
244             else if (eKey.endsWith("-id")) {
245                 jObj.put("resourceInstanceId", eValue)
246                 String resourceName = rt + eValue
247                 jObj.put("resourceType", resourceName)
248             }
249             jObj.put("resourceLinkUrl", rl)
250         }
251         List<RelatedToProperty> rl_props = relationship.getRelatedToProperty()
252         for (RelatedToProperty rl_prop : rl_props) {
253             def eKey = rl_prop.getPropertyKey()
254             def eValue = rl_prop.getPropertyValue()
255             if ((rt.equals("service-instance") && eKey.equals("service-instance.service-instance-name"))
256                     //for overlay/underlay
257                     || (rt.equals("configuration") && eKey.equals("configuration.configuration-type"))) {
258                 jObj.put("resourceType", eValue)
259             }
260         }
261         logger.debug("Relationship related to Resource:" + jObj.toString())
262         return jObj
263     }
264
265     private Relationship getRelationShipFromNode(groovy.util.slurpersupport.Node relationshipNode) {
266         Relationship relationship = new Relationship()
267         def rtn = relationshipNode.childNodes()
268         List<RelationshipData> relationshipDatas = new ArrayList<>()
269         List<RelatedToProperty> relationshipProperties = new ArrayList<>()
270         while (rtn.hasNext()) {
271             groovy.util.slurpersupport.Node node = rtn.next()
272             def key = node.name()
273
274             if(key.equals("related-to")){
275                 def rt = node.text()
276                 relationship.setRelatedTo(rt)
277             } else if (key.equals("related-link")){
278                 def rl = node.text()
279                 relationship.setRelatedLink(rl)
280             } else if (key.equals("relationship-label")){
281                 def label = node.text()
282                 relationship.setRelationshipLabel(label)
283             } else if (key.equals("relationship-data")){
284                 def rData = node.childNodes()
285                 RelationshipData relationshipData = new RelationshipData()
286                 while(rData.hasNext()){
287                     groovy.util.slurpersupport.Node datanode = rData.next()
288                     def dataKey = datanode.name()
289                     if(dataKey.equals("relationship-key")) {
290                         relationshipData.setRelationshipKey(datanode.text())
291                     } else if(dataKey.equals("relationship-value")) {
292                         relationshipData.setRelationshipValue(datanode.text())
293                     }
294                 }
295                 relationshipDatas.add(relationshipData)
296             } else if (key.equals("related-to-property")){
297                 def rProperty = node.childNodes()
298                 RelatedToProperty relationshipProperty = new RelatedToProperty()
299                 while(rProperty.hasNext()){
300                     groovy.util.slurpersupport.Node propnode = rProperty.next()
301
302                     def dataKey = propnode.name()
303                     if(dataKey.equals("property-key")) {
304                         relationshipProperty.setPropertyKey(propnode.text())
305                     } else if(dataKey.equals("property-value")) {
306                         relationshipProperty.setPropertyValue(propnode.text())
307                     }
308
309                 }
310                 relationshipProperties.add(relationshipProperty)
311             }
312
313         }
314         relationship.getRelationshipData().addAll(relationshipDatas)
315         relationship.getRelatedToProperty().addAll(relationshipProperties)
316
317         logger.debug("Relationship related to Resource:" + relationship.toString())
318         return relationship
319     }
320
321    public void getCurrentNS(DelegateExecution execution){
322        logger.info( "======== Start getCurrentNS Process ======== ")
323
324        def currentIndex = execution.getVariable("currentNSIndex")
325        List<String> nsSequence = execution.getVariable("nsSequence")
326        String nsResourceType =  nsSequence.get(currentIndex)
327
328        // GET AAI by Name, not ID, for process convenient
329        execution.setVariable("GENGS_type", "service-instance")
330        execution.setVariable("GENGS_serviceInstanceId", "")
331        execution.setVariable("GENGS_serviceInstanceName", nsResourceType)
332
333        logger.debug("======== COMPLETED getCurrentNS Process ======== ")
334    }
335
336     public void prepareDecomposeService(DelegateExecution execution) {
337         try {
338             logger.debug(" ***** Inside prepareDecomposeService of create generic e2e service ***** ")
339             String modelInvariantUuid = execution.getVariable("model-invariant-id-original")
340             String modelVersionId = execution.getVariable("model-version-id-original")
341
342             String serviceModelInfo = """{
343             "modelInvariantUuid":"${modelInvariantUuid}",
344             "modelUuid":"${modelVersionId}",
345             "modelVersion":""
346              }"""
347             execution.setVariable("serviceModelInfo", serviceModelInfo)
348
349             logger.debug(" ***** Completed prepareDecomposeService of  create generic e2e service ***** ")
350         } catch (Exception ex) {
351             // try error in method block
352             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
353             logger.error(exceptionMessage)
354             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
355         }
356     }
357
358         private void generateRelatedResourceInfo(String response, JSONObject jObj, boolean processRelationship){
359
360                 def xml = new XmlSlurper().parseText(response)
361                 def rtn = xml.childNodes()
362                 while (rtn.hasNext()) {
363                         groovy.util.slurpersupport.Node node = rtn.next()
364                         def key = node.name()
365             if (key.equals("relationship-list") && processRelationship) {
366                 def relns = node.childNodes()
367                 JSONArray jArray = new JSONArray()
368                 while (relns.hasNext()) {
369                     groovy.util.slurpersupport.Node relNode = relns.next()
370                     Relationship relationship = getRelationShipFromNode(relNode)
371                     def relationObj = getRelationShipData(relationship)
372                     jArray.put(relationObj)
373                 }
374                 jObj.put(key, jArray)
375             } else {
376                 def value = node.text()
377                 jObj.put(key, value)
378             }
379                 }
380         }
381
382         private JSONObject getRelatedResourceInAAI (DelegateExecution execution, JSONObject jObj, boolean processRelationship)
383         {
384                 logger.debug(" ***** Started getRelatedResourceInAAI *****")
385
386         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
387                 String urlLink = jObj.get("resourceLinkUrl")
388                 String serviceAaiPath = "${aai_endpoint}${urlLink}"
389
390                 URL url = new URL(serviceAaiPath)
391                 HttpClient client = new HttpClientFactory().newXmlClient(url, ONAPComponents.AAI)
392         client.addBasicAuthHeader(UrnPropertiesReader.getVariable("aai.auth", execution), UrnPropertiesReader.getVariable("mso.msoKey", execution))
393         client.addAdditionalHeader("X-FromAppId", "MSO")
394         client.addAdditionalHeader("X-TransactionId", utils.getRequestID())
395         client.setAcceptType(MediaType.APPLICATION_XML)
396
397                 Response response = client.get()
398                 int responseCode = response.getStatus()
399                 execution.setVariable(Prefix + "GeRelatedResourceResponseCode", responseCode)
400                 logger.debug("  Get RelatedResource code is: " + responseCode)
401
402                 String aaiResponse = response.readEntity(String.class)
403                 execution.setVariable(Prefix + "GetRelatedResourceResponse", aaiResponse)
404
405                 //Process Response
406                 if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
407                         //200 OK 201 CREATED 202 ACCEPTED
408                 {
409                         logger.debug("GET RelatedResource Received a Good Response")
410                         execution.setVariable(Prefix + "SuccessIndicator", true)
411                         execution.setVariable(Prefix + "FoundIndicator", true)
412
413                         generateRelatedResourceInfo(aaiResponse, jObj, processRelationship)
414
415                         //get model-invariant-uuid and model-uuid
416                         String modelInvariantId = ""
417                         String modelUuid = ""
418                         String modelCustomizationId = ""
419                         if(jObj.has("model-invariant-id")) {
420                                 modelInvariantId = jObj.get("model-invariant-id")
421                                 modelUuid = jObj.get("model-version-id")
422                 if (jObj.has("model-customization-id")) {
423                     modelCustomizationId = jObj.get("model-customization-id")
424                 } else {
425                     logger.info("resource customization id is not found for :" + url)
426                 }
427                         }
428
429                         jObj.put("modelInvariantId", modelInvariantId)
430                         jObj.put("modelVersionId", modelUuid)
431                         jObj.put("modelCustomizationId", modelCustomizationId)
432             logger.info("resource detail from AAI:" + jObj)
433                 }
434                 else {
435             String exceptionMessage = "Get RelatedResource Received a Bad Response Code. Response Code is: " + responseCode
436                         logger.error(exceptionMessage)
437             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
438         }
439
440                 logger.debug(" ***** Exit getRelatedResourceInAAI *****")
441                 return jObj
442         }
443
444     public void postDecomposeService(DelegateExecution execution) {
445         logger.debug(" ***** Inside postDecomposeService() of  delete generic e2e service flow ***** ")
446         try {
447             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
448
449             // service model info
450             execution.setVariable("serviceModelInfo", serviceDecomposition.getModelInfo())
451
452             List<Resource> deleteResourceList = serviceDecomposition.getServiceResources()
453             String serviceRelationShip = execution.getVariable("serviceRelationShip")
454             def jsonSlurper = new JsonSlurper()
455             def jsonOutput = new JsonOutput()
456
457             List relationShipList = null
458             if (serviceRelationShip != null) {
459                 relationShipList = jsonSlurper.parseText(serviceRelationShip)
460             }
461
462             List<ImmutablePair<Resource, List<Resource>>> deleteRealResourceList = new ArrayList<ImmutablePair<Resource, List<Resource>>>()
463
464             //Set the real resource instance id to the decomosed resource list
465             //reset the resource instance id , because in the decompose flow ,its a random one.
466             //match the resource-instance-name and the model name
467             if (relationShipList != null) {
468                 relationShipList.each {
469
470                     JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it, true)
471
472                     for (Resource resource : deleteResourceList) {
473
474                         boolean matches = processMatchingResource(resource, obj)
475                         if((matches) && resource.getResourceType().equals(ResourceType.VNF))  {
476                             List<Resource> delGroupList = new ArrayList<Resource>()
477                             JSONArray vfRelationship = obj.getJSONArray("relationship-list")
478                             for (int idx = 0; idx < vfRelationship.length(); idx++) {
479                                 JSONObject vfItem = vfRelationship.getJSONObject(idx)
480                                 JSONObject groupObject = getRelatedResourceInAAI(execution, vfItem, false)
481                                 List<GroupResource> groups = ((VnfResource)resource).getGroups()
482                                 for (GroupResource group : groups){
483                                     if(processMatchingResource(group, groupObject)){
484                                         delGroupList.add(group)
485                                     }
486                                 }
487                             }
488                             def delMap = new ImmutablePair(resource, delGroupList)
489
490                             deleteRealResourceList.add(delMap)
491                         }
492                     }
493                 }
494             }
495
496             // only delete real existing resources
497             execution.setVariable("deleteResourceList", deleteRealResourceList)
498             
499             boolean isDeleteResourceListValid = false
500             if(deleteRealResourceList.size() > 0) {
501                 isDeleteResourceListValid = true
502             }
503             execution.setVariable("isDeleteResourceListValid", isDeleteResourceListValid)
504
505             logger.debug("delete resource list : " + deleteRealResourceList)
506         } catch (Exception ex) {
507             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. processDecomposition() - " + ex.getMessage()
508             logger.error(exceptionMessage)
509             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
510         }
511         logger.debug(" ***** exit postDecomposeService() of  delete generic e2e service flow ***** ")
512     }
513
514     private boolean processMatchingResource(Resource resource, JSONObject obj) {
515         boolean matches = false
516         String modelName = resource.getModelInfo().getModelName()
517
518         String modelCustomizationUuid = resource.getModelInfo().getModelCustomizationUuid()
519         String modelUuid = resource.getModelInfo().getModelUuid()
520         if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) {
521             resource.setResourceId(obj.get("resourceInstanceId"))
522             //deleteRealResourceList.add(resource)
523             matches = true
524         } else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId")) || modelUuid.equals(obj.get("model-version-id")) ) {
525             resource.setResourceId(obj.get("resourceInstanceId"))
526             resource.setResourceInstanceName(obj.get("resourceType"))
527             //deleteRealResourceList.add(resource)
528             matches = true
529         }
530         return matches
531     }
532
533     public void preInitResourcesOperStatus(DelegateExecution execution){
534         logger.debug(" ======== STARTED preInitResourcesOperStatus Process ======== ")
535         try{
536             String serviceId = execution.getVariable("serviceInstanceId")
537             String operationId = execution.getVariable("operationId")
538             String operationType = execution.getVariable("operationType")
539             String resourceTemplateUUIDs = ""
540             String result = "processing"
541             String progress = "0"
542             String reason = ""
543             String operationContent = "Prepare service creation"
544             logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType)
545             serviceId = UriUtils.encode(serviceId,"UTF-8")
546             execution.setVariable("serviceInstanceId", serviceId)
547             execution.setVariable("operationId", operationId)
548             execution.setVariable("operationType", operationType)
549             List<ImmutablePair<Resource, List<Resource>>> deleteResourceList = execution.getVariable("deleteResourceList")
550
551             String serviceRelationShip = execution.getVariable("serviceRelationShip")
552             for (ImmutablePair rc : deleteResourceList) {
553                 Resource resource = rc.getKey()
554                 resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":"
555             }
556
557             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
558             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint", dbAdapterEndpoint)
559
560             String payload =
561                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
562                         xmlns:ns="http://org.onap.so/requestsdb">
563                         <soapenv:Header/>
564                         <soapenv:Body>
565                             <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
566                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
567                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
568                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
569                             <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs>
570                         </ns:initResourceOperationStatus>
571                     </soapenv:Body>
572                 </soapenv:Envelope>"""
573
574             payload = utils.formatXml(payload)
575             execution.setVariable("CVFMI_initResOperStatusRequest", payload)
576             logger.debug("Outgoing initResourceOperationStatus: \n" + payload)
577             logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload)
578
579         }catch(Exception e){
580             logger.debug("Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e)
581             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
582         }
583         logger.debug("======== COMPLETED preInitResourcesOperStatus Process ======== ")
584     }
585     
586     public void prepareUpdateServiceOperationStatus(DelegateExecution execution){
587         logger.debug(" ======== STARTED prepareUpdateServiceOperationStatus Process ======== ")
588         try{
589             String serviceId = execution.getVariable("serviceInstanceId")
590             String operationId = execution.getVariable("operationId")
591             String userId = ""
592             String result = execution.getVariable("result")
593             String progress = execution.getVariable("progress")
594             String reason = ""
595             String operationContent = execution.getVariable("operationContent")
596             
597             serviceId = UriUtils.encode(serviceId,"UTF-8")
598
599             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
600             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
601             logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
602
603             String payload =
604                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
605                         xmlns:ns="http://org.onap.so/requestsdb">
606                         <soapenv:Header/>
607                         <soapenv:Body>
608                             <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
609                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
610                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
611                             <operationType>DELETE</operationType>
612                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
613                             <result>${MsoUtils.xmlEscape(result)}</result>
614                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
615                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
616                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
617                         </ns:updateServiceOperationStatus>
618                     </soapenv:Body>
619                 </soapenv:Envelope>"""
620
621             payload = utils.formatXml(payload)
622             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
623             logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
624
625         }catch(Exception e){
626             logger.error("Exception Occured Processing prepareUpdateServiceOperationStatus. Exception is:\n" + e)
627             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateServiceOperationStatus Method:\n" + e.getMessage())
628         }
629         logger.debug("======== COMPLETED prepareUpdateServiceOperationStatus Process ======== ")
630     }
631
632      /**
633       * post config request.
634       */
635      public void postConfigRequest(execution){
636          //to do
637      }
638
639     /**
640      * Deletes the service instance in aai
641      */
642     public void deleteServiceInstance(DelegateExecution execution) {
643         logger.trace("Entered deleteServiceInstance")
644         try {
645             String globalCustId = execution.getVariable("globalSubscriberId")
646             String serviceType = execution.getVariable("serviceType")
647             String serviceInstanceId = execution.getVariable("serviceInstanceId")
648
649             AAIResourcesClient resourceClient = new AAIResourcesClient()
650             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId)
651             resourceClient.delete(serviceInstanceUri)
652
653             logger.trace("Exited deleteServiceInstance")
654         }catch(Exception e){
655             logger.debug("Error occured within deleteServiceInstance method: " + e)
656             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteServiceInstance from aai")
657         }
658     }
659
660
661 }