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