Merge "Update NSMF workflow to for the E2E Network Slicing requirements"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoActivateCoreNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Tech Mahindra
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.json.JSONObject
26 import org.onap.logging.filter.base.ONAPComponents
27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
29 import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.scripts.RequestDBUtil
32 import org.onap.so.serviceinstancebeans.CloudConfiguration
33 import org.onap.so.serviceinstancebeans.LineOfBusiness
34 import org.onap.so.serviceinstancebeans.ModelInfo
35 import org.onap.so.serviceinstancebeans.ModelType
36 import org.onap.so.serviceinstancebeans.OwningEntity
37 import org.onap.so.serviceinstancebeans.Platform
38 import org.onap.so.serviceinstancebeans.Project
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.onap.so.bpmn.core.UrnPropertiesReader
41 import org.onap.so.rest.catalog.beans.Vnf
42 import org.onap.so.serviceinstancebeans.RequestDetails
43 import org.onap.so.serviceinstancebeans.RequestInfo
44 import org.onap.so.serviceinstancebeans.RequestParameters
45 import org.onap.so.serviceinstancebeans.SubscriberInfo
46 import org.onap.aai.domain.yang.GenericVnf
47 import org.onap.aai.domain.yang.RelatedToProperty
48 import org.onap.aai.domain.yang.Relationship
49 import org.onap.aai.domain.yang.RelationshipData
50 import org.onap.aai.domain.yang.RelationshipList
51 import org.onap.aai.domain.yang.ServiceInstance
52 import org.onap.aai.domain.yang.v19.SliceProfile
53 import org.onap.aai.domain.yang.v19.SliceProfiles
54 import org.slf4j.Logger
55 import org.slf4j.LoggerFactory
56 import org.onap.so.client.HttpClient
57 import org.onap.so.client.HttpClientFactory
58 import org.onap.so.db.request.beans.OperationStatus
59 import org.onap.so.db.request.beans.ResourceOperationStatus
60 import org.onap.aaiclient.client.aai.AAIObjectType
61 import org.onap.aaiclient.client.aai.AAIResourcesClient
62 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
63 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
64 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
65 import com.fasterxml.jackson.databind.ObjectMapper
66
67 import javax.ws.rs.NotFoundException
68 import javax.ws.rs.core.Response
69
70 class DoActivateCoreNSSI extends AbstractServiceTaskProcessor {
71     String Prefix="DACTCNSSI_"
72     private static final Logger logger = LoggerFactory.getLogger(DoActivateCoreNSSI.class);
73     CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
74     private RequestDBUtil requestDBUtil = new RequestDBUtil()
75     ExceptionUtil exceptionUtil = new ExceptionUtil()
76     ObjectMapper mapper = new ObjectMapper();
77
78     JsonUtils jsonUtil = new JsonUtils()
79
80     private final Long TIMEOUT = 60 * 60 * 1000
81
82     @Override
83     public void preProcessRequest(DelegateExecution execution) {
84         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: preProcessRequest ****")
85
86         String operationType = execution.getVariable("operationType")
87         String oStatus= ""
88
89         if(operationType.equals("activateInstance")) {
90             oStatus ="activated"
91         } else {
92             oStatus ="deactivated"
93         }
94
95         execution.setVariable("oStatus", oStatus)
96         String sNssaiListAsString = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "snssaiList")
97
98         logger.debug("sNssaiListAsString "+sNssaiListAsString)
99
100         List<String> sNssaiList = jsonUtil.StringArrayToList(sNssaiListAsString)
101
102         logger.debug("sNssaiList "+sNssaiList)
103
104
105         String sNssai = sNssaiList.get(0)
106         execution.setVariable("sNssai", sNssai)
107
108         logger.debug("sNssai: "+sNssai)
109
110         String serviceType = execution.getVariable("subscriptionServiceType")
111         execution.setVariable("serviceType", serviceType)
112         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: preProcessRequest ****")
113     }
114
115     public void getNetworkInstanceWithSPInstanceAssociatedWithNssiId(DelegateExecution execution) {
116         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getNetworkInstanceWithSPInstanceAssociatedWithNssiId ****")
117         //NSSI Id as service Instance Id to get from Request
118         String serviceInstanceId = execution.getVariable("serviceInstanceID")
119         String errorMsg = "query Network Service Instance from AAI failed"
120         AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
121         Optional<ServiceInstance> nsi = wrapper.asBean(ServiceInstance.class)
122         String networkServiceInstanceName = ""
123         String networkServiceInstanceId =""
124         if(nsi.isPresent()) {
125             List<Relationship> relationshipList = nsi.get().getRelationshipList()?.getRelationship()
126             List spiWithsNssaiAndOrchStatusList = new ArrayList<>()
127
128             for (Relationship relationship : relationshipList) {
129                 String relatedTo = relationship.getRelatedTo()
130                 if (relatedTo == "service-instance") {
131                     List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
132                     List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
133                     for (RelationshipData relationshipData : relationshipDataList) {
134                         if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
135                             execution.setVariable("networkServiceInstanceId", relationshipData.getRelationshipValue())
136                         }
137                     }
138                     for (RelatedToProperty relatedToProperty : relatedToPropertyList) {
139                         if (relatedToProperty.getPropertyKey() == "service-instance.service-instance-name") {
140                             execution.setVariable("networkServiceInstanceName", relatedToProperty.getPropertyValue())
141                         }
142                     }
143                 }
144
145                 //If related to is allotted-Resource
146                 if (relatedTo == "allotted-resource") {
147                     //get slice Profile Instance Id from allotted resource in list by nssi
148                     List<String> sliceProfileInstanceIdList = new ArrayList<>()
149                     List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
150                     for (RelationshipData relationshipData : relationshipDataList) {
151                         if (relationshipData.getRelationshipKey() == "service-instance.service-instance-id") {
152                             sliceProfileInstanceIdList.add(relationshipData.getRelationshipValue())
153                         }
154                     }
155                     for (String sliceProfileServiceInstanceId : sliceProfileInstanceIdList) {
156                         String errorSliceProfileMsg = "Slice Profile Service Instance was not found in aai"
157
158                         //Query Slice Profile Service Instance From AAI by sliceProfileServiceInstanceId
159                         AAIResultWrapper sliceProfileInstanceWrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, sliceProfileServiceInstanceId, errorSliceProfileMsg)
160                         Optional<ServiceInstance> sliceProfileServiceInstance = sliceProfileInstanceWrapper.asBean(ServiceInstance.class)
161                         if (sliceProfileServiceInstance.isPresent()) {
162                             String orchestrationStatus= sliceProfileServiceInstance.get().getOrchestrationStatus()
163                             String sNssai = sliceProfileServiceInstance.get().getSliceProfiles().getSliceProfile().get(0).getSNssai()
164                             if(sNssai.equals(execution.getVariable("sNssai"))) {
165                                 orchestrationStatus = execution.getVariable("oStatus")
166                                 //Slice Profile Service Instance to be updated in AAI
167                                 execution.setVariable("sliceProfileServiceInstance", sliceProfileServiceInstance)
168                             }
169
170                             Map<String, Object> spiWithsNssaiAndOrchStatus = new LinkedHashMap<>()
171                             spiWithsNssaiAndOrchStatus.put("snssai", sNssai)
172                             spiWithsNssaiAndOrchStatus.put("status", orchestrationStatus)
173                             spiWithsNssaiAndOrchStatusList.add(spiWithsNssaiAndOrchStatus)
174                         }
175                     }
176                 }
177             }
178             execution.setVariable("snssaiAndOrchStatusList", spiWithsNssaiAndOrchStatusList)
179         }
180         logger.debug("NSSI Id: ${serviceInstanceId}, network Service Instance Id: ${networkServiceInstanceId}, serviceName: ${networkServiceInstanceName}")
181         //Get ServiceInstance Relationships
182         getServiceInstanceRelationships(execution)
183         //Get Vnf Relationships
184         getVnfRelationships(execution)
185         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getNetworkInstanceWithSPInstanceAssociatedWithNssiId ****")
186     }
187
188
189     private String prepareVnfInstanceParamsJson(DelegateExecution execution) {
190         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareVnfInstanceParamsJson ****")
191         List instanceParamsvalues = execution.getVariable("snssaiAndOrchStatusList")
192         Map<String, Object> nSsai= new LinkedHashMap<>()
193         nSsai.put("sNssai", instanceParamsvalues)
194         String supportedsNssaiJson = mapper.writeValueAsString(nSsai)
195         //SupportedNssai
196         Map<String, Object> supportedNssai= new LinkedHashMap<>()
197         supportedNssai.put("supportedNssai", supportedsNssaiJson)
198         logger.debug("****  supportedsNssaiJson**** "+supportedNssai)
199         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareVnfInstanceParamsJson ****")
200         return supportedNssai
201     }
202
203     private void getServiceInstanceRelationships(DelegateExecution execution) {
204         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getServiceInstanceRelationships ****")
205         String serviceInstanceId = execution.getVariable("networkServiceInstanceId")
206         logger.debug("**** serviceInstanceId :: getServiceInstanceRelationships  :: "+serviceInstanceId)
207         String errorMsg = "query Network Service Instance from AAI failed"
208         AAIResultWrapper wrapper = queryAAI(execution, AAIObjectType.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
209         Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
210
211         String networkServiceModelInvariantUuid = si.get().getModelInvariantId()
212         execution.setVariable("networkServiceModelInvariantUuid", networkServiceModelInvariantUuid)
213         if(si.isPresent()) {
214             List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
215             for (Relationship relationship : relationshipList) {
216                 String relatedTo = relationship.getRelatedTo()
217                 if (relatedTo == "owning-entity") {
218                     List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
219                     for (RelationshipData relationshipData : relationshipDataList) {
220                         if (relationshipData.getRelationshipKey() == "owning-entity.owning-entity-id") {
221                             execution.setVariable("owningEntityId", relationshipData.getRelationshipValue())
222                         }
223                     }
224                 } else if (relatedTo == "generic-vnf") {
225                     List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
226                     List<RelatedToProperty> relatedToPropertyList = relationship.getRelatedToProperty()
227
228                     //Get VnfId
229                     for (RelationshipData relationshipData : relationshipDataList) {
230                         if (relationshipData.getRelationshipKey() == "generic-vnf.vnf-id") {
231                             execution.setVariable("vnfId", relationshipData.getRelationshipValue())
232                             String vnfId = relationshipData.getRelationshipValue()
233                             logger.debug("vnfId   :"+vnfId)
234                         }
235                     }
236                 } else if (relatedTo == "project") {
237                     List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
238                     for (RelationshipData relationshipData : relationshipDataList) {
239                         if (relationshipData.getRelationshipKey() == "project.project-name") {
240                             execution.setVariable("projectName", relationshipData.getRelationshipValue())
241                         }
242                     }
243                 }
244             }
245             logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceInstanceRelationships ****")
246         }
247     }
248
249     private void getVnfRelationships(DelegateExecution execution) {
250
251         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: getVnfRelationships ****")
252         String msg = "query Generic Vnf from AAI failed"
253         try {
254             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, execution.getVariable('vnfId'))
255             if (!getAAIClient().exists(uri)) {
256                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
257             }
258             AAIResultWrapper wrapper = getAAIClient().get(uri, NotFoundException.class)
259             Optional<GenericVnf> vnf = wrapper.asBean(GenericVnf.class)
260             if(vnf.isPresent()) {
261                 List<Relationship> relationshipList = vnf.get().getRelationshipList()?.getRelationship()
262                 for (Relationship relationship : relationshipList) {
263                     String relatedTo = relationship.getRelatedTo()
264                     if (relatedTo == "tenant") {
265                         List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
266                         for (RelationshipData relationshipData : relationshipDataList) {
267                             if (relationshipData.getRelationshipKey() == "tenant.tenant-id") {
268                                 execution.setVariable("tenantId", relationshipData.getRelationshipValue())
269                             }
270                         }
271                     } else if (relatedTo == "cloud-region") {
272                         List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
273
274                         for (RelationshipData relationshipData : relationshipDataList) {
275                             if (relationshipData.getRelationshipKey() == "cloud-region.cloud-owner") {
276                                 execution.setVariable("cloudOwner", relationshipData.getRelationshipValue())
277                             } else if (relationshipData.getRelationshipKey() == "cloud-region.cloud-region-id") {
278                                 execution.setVariable("lcpCloudRegionId", relationshipData.getRelationshipValue())
279                             }
280                         }
281                     } else if (relatedTo == "platform") {
282                         List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
283                         for (RelationshipData relationshipData : relationshipDataList) {
284                             if (relationshipData.getRelationshipKey() == "platform.platform-name") {
285                                 execution.setVariable("platformName", relationshipData.getRelationshipValue())
286                             }
287                         }
288                     } else if (relatedTo == "line-of-business") {
289                         List<RelationshipData> relationshipDataList = relationship.getRelationshipData()
290                         for (RelationshipData relationshipData : relationshipDataList) {
291                             if (relationshipData.getRelationshipKey() == "line-of-business.line-of-business-name") {
292                                 execution.setVariable("lineOfBusinessName", relationshipData.getRelationshipValue())
293                             }
294                         }
295                     }
296                 }
297             }
298         } catch(BpmnError e){
299             throw e
300         } catch (Exception ex){
301             msg = "Exception in getVnfRelationships " + ex.getMessage()
302             logger.debug(msg)
303             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
304         }
305         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getVnfRelationships ****")
306     }
307
308
309     /**
310      * query AAI
311      * @param execution
312      * @param aaiObjectType
313      * @param instanceId
314      * @return AAIResultWrapper
315      */
316     private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectType aaiObjectType, String instanceId, String errorMsg) {
317         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: queryAAI ****")
318
319         String globalSubscriberId = execution.getVariable("globalSubscriberId")
320         String serviceType = execution.getVariable("serviceType")
321
322         AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(aaiObjectType, globalSubscriberId, serviceType, instanceId)
323         if (!getAAIClient().exists(resourceUri)) {
324             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
325         }
326         AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
327
328         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: queryAAI ****")
329         return wrapper
330     }
331
332     public void getServiceVNFAndVFsFromCatalogDB(DelegateExecution execution) {
333         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceVNFAndVFsFromCatalogDB ****")
334
335         String modelInvariantUuid = execution.getVariable("networkServiceModelInvariantUuid")
336
337         try{
338             CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
339             String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution, modelInvariantUuid)
340             logger.debug("***** JSON IS: "+json)
341
342             String serviceVnfs = jsonUtil.getJsonValue(json, "serviceResources.serviceVnfs") ?: ""
343             String serviceModelInfo = jsonUtil.getJsonValue(json, "serviceResources.modelInfo") ?: ""
344
345
346             execution.setVariable("serviceVnfs",serviceVnfs)
347             execution.setVariable("serviceModelInfo", serviceModelInfo)
348             logger.debug(Prefix +" ***** serviceVnfs is: "+ serviceVnfs)
349         }catch(BpmnError e){
350             throw e
351         } catch (Exception ex){
352             String msg = "Exception in getServiceVNFAndVFsFromCatalogDB " + ex.getMessage()
353             logger.debug(msg)
354             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
355         }
356         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: getServiceVNFAndVFsFromCatalogDB ****")
357     }
358
359     public void prepareSOMacroRequestPayLoad(DelegateExecution execution) {
360         logger.debug("**** Enter DoActivateCoreNSSI ::: prepareSOMacroRequestPayLoad ****")
361         String json = execution.getVariable("serviceVnfs")
362         logger.debug(">>>> json "+json)
363         List<Object> vnfList = mapper.readValue(json, List.class);
364         logger.debug("vnfList:  "+vnfList)
365         Map<String,Object> serviceMap = mapper.readValue(execution.getVariable("serviceModelInfo"), Map.class);
366         ModelInfo serviceModelInfo = new ModelInfo()
367         serviceModelInfo.setModelType(ModelType.service)
368         serviceModelInfo.setModelInvariantId(serviceMap.get("modelInvariantUuid"))
369         serviceModelInfo.setModelVersionId(serviceMap.get("modelUuid"))
370         serviceModelInfo.setModelName(serviceMap.get("modelName"))
371         serviceModelInfo.setModelVersion(serviceMap.get("modelVersion"))
372
373         logger.debug("serviceModelInfo:  "+serviceModelInfo)
374         //List of Vnfs
375         List<Object> vnfModelInfoList = new ArrayList<>()
376
377         Map vnfMap = vnfList.get(0)
378         ModelInfo vnfModelInfo = vnfMap.get("modelInfo")
379         logger.debug("vnfModelInfo "+vnfModelInfo)
380
381         //List of VFModules
382         List<Map<String, Object>> vfModuleList = vnfMap.get("vfModules")
383         logger.debug("vfModuleList "+vfModuleList)
384
385         //List of VfModules
386         List<ModelInfo> vfModelInfoList = new ArrayList<>()
387
388         //Traverse VFModules List and add in vfModelInfoList
389         for (vfModule in vfModuleList) {
390             ModelInfo vfModelInfo = vfModule.get("modelInfo")
391             logger.debug("vfModelInfo "+vfModelInfo)
392             vfModelInfoList.add(vfModelInfo)
393         }
394
395         //RequestInfo
396         RequestInfo requestInfo = new RequestInfo()
397
398         //Dummy Product FamilyId
399         requestInfo.setProductFamilyId("test1234")
400         requestInfo.setSource("VID")
401         requestInfo.setInstanceName(execution.getVariable("networkServiceInstanceName"))
402         requestInfo.setSuppressRollback(false)
403         requestInfo.setRequestorId("NBI")
404
405         //Service Level InstanceParams
406         List<Map<String, Object>> serviceParams = new ArrayList<>()
407         Map<String, Object> serviceParamsValues = new LinkedHashMap<>()
408         serviceParams.add(serviceParamsValues)
409
410         //Cloud Configuration
411         CloudConfiguration cloudConfiguration = new CloudConfiguration()
412         cloudConfiguration.setLcpCloudRegionId(execution.getVariable("lcpCloudRegionId"))
413         cloudConfiguration.setTenantId(execution.getVariable("tenantId"))
414         cloudConfiguration.setCloudOwner(execution.getVariable("cloudOwner"))
415
416         //VFModules List
417         List<Map<String, Object>> vfModules = new ArrayList<>()
418         for (ModelInfo vfModuleModelInfo : vfModelInfoList) {
419             //Individual VFModule List
420             Map<String, Object> vfModuleValues = new LinkedHashMap<>()
421             vfModuleValues.put("modelInfo", vfModuleModelInfo)
422             vfModuleValues.put("instanceName", vfModuleModelInfo.getModelInstanceName())
423
424             //VFModule InstanceParams should be empty or this field should not be there?
425             List<Map<String, Object>> vfModuleInstanceParams = new ArrayList<>()
426             vfModuleValues.put("instanceParams", vfModuleInstanceParams)
427         }
428
429         //Vnf intsanceParams
430         ObjectMapper objectMapper = new ObjectMapper();
431         Map<String, Object> sliceProfile = objectMapper.readValue(execution.getVariable("sliceProfile"), Map.class);
432
433         List vnfInstanceParamsList = new ArrayList<>()
434         String supportedsNssaiJson= prepareVnfInstanceParamsJson(execution)
435         vnfInstanceParamsList.add(supportedsNssaiJson)
436
437         Platform platform = new Platform()
438         platform.setPlatformName(execution.getVariable("platform"))
439
440         LineOfBusiness lineOfbusiness = new LineOfBusiness()
441         lineOfbusiness.setLineOfBusinessName(execution.getVariable("lineOfBusiness"))
442
443         //Vnf Values
444         Map<String, Object> vnfValues = new LinkedHashMap<>()
445         vnfValues.put("lineOfBusiness", lineOfbusiness)
446         vnfValues.put("platform", platform)
447         vnfValues.put("productFamilyId", "test1234")
448         vnfValues.put("cloudConfiguration", cloudConfiguration)
449         vnfValues.put("vfModules", vfModules)
450         vnfValues.put("modelInfo", vnfModelInfo)
451         vnfValues.put("instanceName", execution.getVariable("vnfInstanceName"))
452         vnfValues.put("instanceParams",vnfInstanceParamsList)
453
454         vnfModelInfoList.add(vnfValues)
455         //Service Level Resources
456         Map<String, Object> serviceResources = new LinkedHashMap<>()
457         serviceResources.put("vnfs", vnfModelInfoList)
458
459         //Service Values
460         Map<String, Object> serviceValues = new LinkedHashMap<>()
461         serviceValues.put("modelInfo", serviceModelInfo)
462         serviceValues.put("instanceName", execution.getVariable("networkServiceInstanceName"))
463         serviceValues.put("resources", serviceResources)
464         serviceValues.put("instanceParams", serviceParams)
465
466         //UserParams Values
467         Map<String, Object> userParamsValues = new LinkedHashMap<>()
468
469         Map<String, Object> homingSolution = new LinkedHashMap<>()
470         homingSolution.put("Homing_Solution", "none")
471
472         userParamsValues.put("service", serviceValues)
473
474         //UserParams
475         List<Map<String, Object>> userParams = new ArrayList<>()
476         userParams.add(homingSolution)
477         userParams.add(userParamsValues)
478
479         //Request Parameters
480         RequestParameters requestParameters = new RequestParameters()
481         requestParameters.setaLaCarte(false)
482         requestParameters.setSubscriptionServiceType(execution.getVariable("serviceType"))
483         requestParameters.setUserParams(userParams)
484
485         //SubscriberInfo
486         SubscriberInfo subscriberInfo = new SubscriberInfo()
487         subscriberInfo.setGlobalSubscriberId(execution.getVariable("globalSubscriberId"))
488
489         //Owning Entity
490         OwningEntity owningEntity = new OwningEntity()
491         owningEntity.setOwningEntityId(execution.getVariable("owningEntityId"))
492
493         //Project
494         Project project = new Project()
495         project.setProjectName(execution.getVariable("projectName"))
496
497         RequestDetails requestDetails = new RequestDetails()
498         requestDetails.setModelInfo(serviceModelInfo)
499         requestDetails.setSubscriberInfo(subscriberInfo)
500         requestDetails.setRequestInfo(requestInfo)
501         requestDetails.setRequestParameters(requestParameters)
502         requestDetails.setCloudConfiguration(cloudConfiguration)
503         requestDetails.setOwningEntity(owningEntity)
504         requestDetails.setProject(project)
505
506         Map<String, Object> requestDetailsMap = new LinkedHashMap<>()
507         requestDetailsMap.put("requestDetails", requestDetails)
508         String requestPayload = objectMapper.writeValueAsString(requestDetailsMap)
509
510         logger.debug("requestDetails "+requestPayload)
511         execution.setVariable("requestPayload", requestPayload)
512
513         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareSOMacroRequestPayLoad ****")
514     }
515
516     public void sendPutRequestToSOMacro(DelegateExecution execution) {
517
518         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: sendPutRequestToSOMacro ****")
519         try {
520             String msoEndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
521             String url = msoEndpoint+"/serviceInstantiation/v7/serviceInstances/"+execution.getVariable("networkServiceInstanceId")+"/vnfs/"+execution.getVariable("vnfId")
522             String requestBody = execution.getVariable("requestPayload")
523             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
524             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
525             String basicAuthValue = utils.encrypt(basicAuth, msoKey)
526             String encodeString = utils.getBasicAuth(basicAuthValue, msoKey)
527
528             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
529             httpClient.addAdditionalHeader("Authorization", encodeString)
530             httpClient.addAdditionalHeader("Accept", "application/json")
531             Response httpResponse = httpClient.put(requestBody)
532             handleSOResponse(httpResponse, execution)
533
534         } catch (BpmnError e) {
535             throw e
536         } catch (any) {
537             String msg = "Exception in DoActivateCoreNSSSI " + any.getCause()
538             logger.error(msg)
539             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
540         }
541         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: sendPostRequestToSOMacro ****")
542     }
543
544     /**
545      * Handle SO Response for PUT and prepare update operation status
546      * @param execution
547      */
548     private void handleSOResponse(Response httpResponse, DelegateExecution execution){
549         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: handleSOResponse ****")
550
551         int soResponseCode = httpResponse.getStatus()
552         logger.debug("soResponseCode : "+soResponseCode)
553
554         if (soResponseCode >= 200 && soResponseCode < 204 && httpResponse.hasEntity()) {
555             String soResponse = httpResponse.readEntity(String.class)
556             String operationId = execution.getVariable("operationId")
557             def macroOperationId = jsonUtil.getJsonValue(soResponse, "operationId")
558             execution.setVariable("macroOperationId", macroOperationId)
559             execution.setVariable("isSOTimeOut", "no")
560             execution.setVariable("isSOResponseSucceed","yes")
561         }
562         else
563         {
564             String serviceName = execution.getVariable("serviceInstanceName")
565             execution.setVariable("isSOResponseSucceed","no")
566             prepareFailedOperationStatusUpdate(execution)
567         }
568
569         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: handleSOResponse ****")
570     }
571
572     /**
573      * prepare to call sub process CheckProcessStatus
574      * @param execution
575      */
576     void prepareCallCheckProcessStatus(DelegateExecution execution){
577         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareCallCheckProcessStatus ****")
578         def successConditions = new ArrayList<>()
579         successConditions.add("finished")
580         execution.setVariable("successConditions", successConditions)
581         def errorConditions = new ArrayList<>()
582         errorConditions.add("error")
583         execution.setVariable("errorConditions", errorConditions)
584         execution.setVariable("processServiceType", "Network service")
585         execution.setVariable("subOperationType", "PUT")
586         execution.setVariable("initProgress", 20)
587         execution.setVariable("endProgress",90)
588         execution.setVariable("timeOut", TIMEOUT)
589         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareCallCheckProcessStatus ****")
590     }
591
592     void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
593
594         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: prepareUpdateResourceOperationStatus ****")
595
596         String nssiOperationId = execution.getVariable("nssiOperationId")
597         execution.setVariable("operationId", nssiOperationId)
598         //Prepare Update Status for PUT failure and success
599         if(execution.getVariable("isTimeOut").equals("YES")) {
600             logger.debug("TIMEOUT - SO PUT Failure")
601             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
602         }
603         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: prepareUpdateResourceOperationStatus ****")
604     }
605
606     void updateSliceProfileOrchestrationStatus(DelegateExecution execution) {
607
608         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: updateSliceProfileOrchestrationStatus ****")
609
610         String globalCustId = execution.getVariable("globalSubscriberId")
611         String serviceType = execution.getVariable("serviceType")
612         String oStatus = execution.getVariable("oStatus")
613
614         ServiceInstance si = execution.getVariable("sliceProfileServiceInstance")
615         String sliceProfileInstanceId = si.getServiceInstanceId()
616         si.setOrchestrationStatus(oStatus)
617
618         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
619                 globalCustId, serviceType, sliceProfileInstanceId)
620         try {
621
622             Response response = getAAIClient().update(uri, si)
623
624             if(response.getStatus()!=200 || response.getStatus()!=201 || response.getStatus()!=202) {
625                 exceptionUtil.buildAndThrowWorkflowException(execution, response.getStatus(), "AAI failed to update sliceProlie service Instance orchestration status")
626             } else {
627                 setResourceOperationStatus(execution)
628             }
629         } catch (Exception e) {
630             logger.info("Update OrchestrationStatus in AAI failed")
631             String msg = "Update OrchestrationStatus in AAI failed, " + e.getMessage()
632             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
633         }
634
635         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: updateSliceProfileOrchestrationStatus ****")
636     }
637
638     /**
639      * prepare ResourceOperation status
640      * @param execution
641      * @param operationType
642      */
643     private void setResourceOperationStatus(DelegateExecution execution) {
644
645         logger.debug(Prefix +" **** Enter DoActivateCoreNSSI ::: setResourceOperationStatus ****")
646
647         String serviceId = execution.getVariable("nssiId")
648         String jobId = execution.getVariable("jobId")
649         String nsiId = execution.getVariable("nsiId")
650         String operationType = execution.getVariable("operationType")
651         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
652         resourceOperationStatus.setServiceId(serviceId)
653         resourceOperationStatus.setOperationId(jobId)
654         resourceOperationStatus.setResourceTemplateUUID(nsiId)
655         resourceOperationStatus.setOperType(operationType)
656         resourceOperationStatus.setStatus("finished")
657         resourceOperationStatus.setProgress("100")
658         resourceOperationStatus.setStatusDescription("Core Activation Successful")
659         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
660
661         logger.debug(Prefix +" **** Exit DoActivateCoreNSSI ::: setResourceOperationStatus ****")
662     }
663
664     void prepareFailedOperationStatusUpdate(DelegateExecution execution){
665         logger.debug(Prefix + " **** Enter DoActivateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
666
667         String serviceId = execution.getVariable("nssiId")
668         String jobId = execution.getVariable("jobId")
669         String nsiId = execution.getVariable("nsiId")
670         String operationType = execution.getVariable("operationType")
671
672         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
673         resourceOperationStatus.setServiceId(serviceId)
674         resourceOperationStatus.setOperationId(jobId)
675         resourceOperationStatus.setResourceTemplateUUID(nsiId)
676         resourceOperationStatus.setOperType(operationType)
677         resourceOperationStatus.setProgress(0)
678         resourceOperationStatus.setStatus("failed")
679         resourceOperationStatus.setStatusDescription("Core NSSI Activation Failed")
680         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
681
682         logger.debug(Prefix + " **** Exit DoActivateCoreNSSI ::: prepareFailedOperationStatusUpdate ****")
683     }
684
685 }