Merge "Fix serviceProfile serialize"
[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.aaiclient.client.aai.AAIObjectType
51 import org.onap.aaiclient.client.aai.AAIResourcesClient
52 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
53 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
54 import org.onap.aaiclient.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                         if (serviceDecomposition.getServiceType().equals("MDONS_OTN")){
454                            for (Resource resource : deleteResourceList) {
455                                 String serviceName = execution.getVariable("serviceInstanceName")
456                                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
457                                 resource.setResourceId(serviceInstanceId)
458                                 resource.setResourceInstanceName(serviceName)
459                                 def delMap = new ImmutablePair(resource, null)
460                                 deleteRealResourceList.add(delMap)
461                            }
462                         } else{
463             String serviceRelationShip = execution.getVariable("serviceRelationShip")
464             def jsonSlurper = new JsonSlurper()
465             def jsonOutput = new JsonOutput()
466
467             List relationShipList = null
468             if (serviceRelationShip != null) {
469                 relationShipList = jsonSlurper.parseText(serviceRelationShip)
470             }
471
472             List<ImmutablePair<Resource, List<Resource>>> deleteRealResourceList = new ArrayList<ImmutablePair<Resource, List<Resource>>>()
473
474             //Set the real resource instance id to the decomosed resource list
475             //reset the resource instance id , because in the decompose flow ,its a random one.
476             //match the resource-instance-name and the model name
477             if (relationShipList != null) {
478                 relationShipList.each {
479
480                     JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it, true)
481
482                     for (Resource resource : deleteResourceList) {
483
484                         boolean matches = processMatchingResource(resource, obj)
485                         if((matches) && resource.getResourceType().equals(ResourceType.VNF))  {
486                             List<Resource> delGroupList = new ArrayList<Resource>()
487                             JSONArray vfRelationship = obj.getJSONArray("relationship-list")
488                             for (int idx = 0; idx < vfRelationship.length(); idx++) {
489                                 JSONObject vfItem = vfRelationship.getJSONObject(idx)
490                                 JSONObject groupObject = getRelatedResourceInAAI(execution, vfItem, false)
491                                 List<GroupResource> groups = ((VnfResource)resource).getGroups()
492                                 for (GroupResource group : groups){
493                                     if(processMatchingResource(group, groupObject)){
494                                         delGroupList.add(group)
495                                     }
496                                 }
497                             }
498                             def delMap = new ImmutablePair(resource, delGroupList)
499
500                             deleteRealResourceList.add(delMap)
501                         }
502                     }
503                 }
504             }
505                         }
506
507             // only delete real existing resources
508             execution.setVariable("deleteResourceList", deleteRealResourceList)
509             
510             boolean isDeleteResourceListValid = false
511             if(deleteRealResourceList.size() > 0) {
512                 isDeleteResourceListValid = true
513             }
514             execution.setVariable("isDeleteResourceListValid", isDeleteResourceListValid)
515
516             logger.debug("delete resource list : " + deleteRealResourceList)
517         } catch (Exception ex) {
518             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. processDecomposition() - " + ex.getMessage()
519             logger.error(exceptionMessage)
520             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
521         }
522         logger.debug(" ***** exit postDecomposeService() of  delete generic e2e service flow ***** ")
523     }
524
525     private boolean processMatchingResource(Resource resource, JSONObject obj) {
526         boolean matches = false
527         String modelName = resource.getModelInfo().getModelName()
528
529         String modelCustomizationUuid = resource.getModelInfo().getModelCustomizationUuid()
530         String modelUuid = resource.getModelInfo().getModelUuid()
531         if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) {
532             resource.setResourceId(obj.get("resourceInstanceId"))
533             //deleteRealResourceList.add(resource)
534             matches = true
535         } else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId")) || modelUuid.equals(obj.get("model-version-id")) ) {
536             resource.setResourceId(obj.get("resourceInstanceId"))
537             resource.setResourceInstanceName(obj.get("resourceType"))
538             //deleteRealResourceList.add(resource)
539             matches = true
540         }
541         return matches
542     }
543
544     public void preInitResourcesOperStatus(DelegateExecution execution){
545         logger.debug(" ======== STARTED preInitResourcesOperStatus Process ======== ")
546         try{
547             String serviceId = execution.getVariable("serviceInstanceId")
548             String operationId = execution.getVariable("operationId")
549             String operationType = execution.getVariable("operationType")
550             String resourceTemplateUUIDs = ""
551             String result = "processing"
552             String progress = "0"
553             String reason = ""
554             String operationContent = "Prepare service creation"
555             logger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType)
556             serviceId = UriUtils.encode(serviceId,"UTF-8")
557             execution.setVariable("serviceInstanceId", serviceId)
558             execution.setVariable("operationId", operationId)
559             execution.setVariable("operationType", operationType)
560             List<ImmutablePair<Resource, List<Resource>>> deleteResourceList = execution.getVariable("deleteResourceList")
561
562             String serviceRelationShip = execution.getVariable("serviceRelationShip")
563             for (ImmutablePair rc : deleteResourceList) {
564                 Resource resource = rc.getKey()
565                 resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":"
566             }
567
568             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
569             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint", dbAdapterEndpoint)
570
571             String payload =
572                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
573                         xmlns:ns="http://org.onap.so/requestsdb">
574                         <soapenv:Header/>
575                         <soapenv:Body>
576                             <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
577                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
578                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
579                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
580                             <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs>
581                         </ns:initResourceOperationStatus>
582                     </soapenv:Body>
583                 </soapenv:Envelope>"""
584
585             payload = utils.formatXml(payload)
586             execution.setVariable("CVFMI_initResOperStatusRequest", payload)
587             logger.debug("Outgoing initResourceOperationStatus: \n" + payload)
588             logger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload)
589
590         }catch(Exception e){
591             logger.debug("Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e)
592             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
593         }
594         logger.debug("======== COMPLETED preInitResourcesOperStatus Process ======== ")
595     }
596     
597     public void prepareUpdateServiceOperationStatus(DelegateExecution execution){
598         logger.debug(" ======== STARTED prepareUpdateServiceOperationStatus Process ======== ")
599         try{
600             String serviceId = execution.getVariable("serviceInstanceId")
601             String operationId = execution.getVariable("operationId")
602             String userId = ""
603             String result = execution.getVariable("result")
604             String progress = execution.getVariable("progress")
605             String reason = ""
606             String operationContent = execution.getVariable("operationContent")
607             
608             serviceId = UriUtils.encode(serviceId,"UTF-8")
609
610             def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
611             execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
612             logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint)
613
614             String payload =
615                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
616                         xmlns:ns="http://org.onap.so/requestsdb">
617                         <soapenv:Header/>
618                         <soapenv:Body>
619                             <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
620                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
621                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
622                             <operationType>DELETE</operationType>
623                             <userId>${MsoUtils.xmlEscape(userId)}</userId>
624                             <result>${MsoUtils.xmlEscape(result)}</result>
625                             <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent>
626                             <progress>${MsoUtils.xmlEscape(progress)}</progress>
627                             <reason>${MsoUtils.xmlEscape(reason)}</reason>
628                         </ns:updateServiceOperationStatus>
629                     </soapenv:Body>
630                 </soapenv:Envelope>"""
631
632             payload = utils.formatXml(payload)
633             execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload)
634             logger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload)
635
636         }catch(Exception e){
637             logger.error("Exception Occured Processing prepareUpdateServiceOperationStatus. Exception is:\n" + e)
638             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateServiceOperationStatus Method:\n" + e.getMessage())
639         }
640         logger.debug("======== COMPLETED prepareUpdateServiceOperationStatus Process ======== ")
641     }
642
643      /**
644       * post config request.
645       */
646      public void postConfigRequest(execution){
647          //to do
648      }
649
650     /**
651      * Deletes the service instance in aai
652      */
653     public void deleteServiceInstance(DelegateExecution execution) {
654         logger.trace("Entered deleteServiceInstance")
655         try {
656             String globalCustId = execution.getVariable("globalSubscriberId")
657             String serviceType = execution.getVariable("serviceType")
658             String serviceInstanceId = execution.getVariable("serviceInstanceId")
659
660             AAIResourcesClient resourceClient = new AAIResourcesClient()
661             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId)
662             resourceClient.delete(serviceInstanceUri)
663
664             logger.trace("Exited deleteServiceInstance")
665         }catch(Exception e){
666             logger.debug("Error occured within deleteServiceInstance method: " + e)
667             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteServiceInstance from aai")
668         }
669     }
670
671
672 }