Use cloud configuration from Vnf
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / bpmn / servicedecomposition / tasks / BBInputSetup.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Modifications Copyright (c) 2020 Nokia
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.so.bpmn.servicedecomposition.tasks;
26
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.Optional;
33 import java.util.UUID;
34 import org.apache.commons.lang3.StringUtils;
35 import org.camunda.bpm.engine.delegate.DelegateExecution;
36 import org.camunda.bpm.engine.delegate.JavaDelegate;
37 import org.javatuples.Pair;
38 import org.onap.aaiclient.client.aai.AAICommonObjectMapperProvider;
39 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
40 import org.onap.aaiclient.client.aai.entities.Relationships;
41 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
42 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
43 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
44 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types;
45 import org.onap.so.bpmn.common.BuildingBlockExecution;
46 import org.onap.so.bpmn.common.DelegateExecutionImpl;
47 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
48 import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection;
49 import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
50 import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
51 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
52 import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup;
53 import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network;
54 import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness;
55 import org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy;
56 import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity;
57 import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform;
58 import org.onap.so.bpmn.servicedecomposition.bbobjects.Pnf;
59 import org.onap.so.bpmn.servicedecomposition.bbobjects.Project;
60 import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference;
61 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
62 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy;
63 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription;
64 import org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant;
65 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
66 import org.onap.so.bpmn.servicedecomposition.bbobjects.Vnfc;
67 import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup;
68 import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding;
69 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
70 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
71 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
72 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
73 import org.onap.so.bpmn.servicedecomposition.entities.ServiceModel;
74 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
75 import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext;
76 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
77 import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.NoServiceInstanceFoundException;
78 import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ResourceNotFoundException;
79 import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ServiceModelNotFoundException;
80 import org.onap.so.client.exception.ExceptionBuilder;
81 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
82 import org.onap.so.db.catalog.beans.CollectionResource;
83 import org.onap.so.db.catalog.beans.CollectionResourceCustomization;
84 import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization;
85 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
86 import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
87 import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
88 import org.onap.so.db.catalog.beans.OrchestrationStatus;
89 import org.onap.so.db.catalog.beans.Service;
90 import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization;
91 import org.onap.so.db.catalog.beans.VfModuleCustomization;
92 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
93 import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
94 import org.onap.so.db.request.beans.InfraActiveRequests;
95 import org.onap.so.serviceinstancebeans.CloudConfiguration;
96 import org.onap.so.serviceinstancebeans.ModelInfo;
97 import org.onap.so.serviceinstancebeans.ModelType;
98 import org.onap.so.serviceinstancebeans.Networks;
99 import org.onap.so.serviceinstancebeans.RelatedInstance;
100 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
101 import org.onap.so.serviceinstancebeans.RequestDetails;
102 import org.onap.so.serviceinstancebeans.RequestParameters;
103 import org.onap.so.serviceinstancebeans.Resources;
104 import org.onap.so.serviceinstancebeans.VfModules;
105 import org.onap.so.serviceinstancebeans.Vnfs;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
108 import org.springframework.beans.factory.annotation.Autowired;
109 import org.springframework.stereotype.Component;
110 import com.fasterxml.jackson.databind.ObjectMapper;
111 import com.fasterxml.jackson.databind.SerializationFeature;
112
113 @Component("BBInputSetup")
114 public class BBInputSetup implements JavaDelegate {
115
116     private static final Logger logger = LoggerFactory.getLogger(BBInputSetup.class);
117     private static final String FLOW_VAR_NAME = "flowToBeCalled";
118     private static final String LOOKUP_KEY_MAP_VAR_NAME = "lookupKeyMap";
119     private static final String GBB_INPUT_VAR_NAME = "gBBInput";
120     private static final String EXECUTE_BB_VAR_NAME = "buildingBlock";
121     private static final String VOLUME_GROUP = "VolumeGroup";
122     private static final String VF_MODULE = "VfModule";
123     private static final String NETWORK = "Network";
124     private static final String VNF = "Vnf";
125     private static final String PNF = "Pnf";
126     private static final String NETWORK_COLLECTION = "NetworkCollection";
127     private static final String PREPROV = "PREPROV";
128     private static final String CREATEVOLUME = "CreateVolume";
129     private static final String CONTROLLER = "Controller";
130
131     @Autowired
132     private BBInputSetupUtils bbInputSetupUtils;
133
134     @Autowired
135     private BBInputSetupMapperLayer mapperLayer;
136
137     @Autowired
138     private CloudInfoFromAAI cloudInfoFromAAI;
139
140     @Autowired
141     private ExceptionBuilder exceptionUtil;
142
143     private ObjectMapper mapper = new ObjectMapper();
144
145     public BBInputSetupUtils getBbInputSetupUtils() {
146         return bbInputSetupUtils;
147     }
148
149     public void setCloudInfoFromAAI(CloudInfoFromAAI cloudInfoFromAAI) {
150         this.cloudInfoFromAAI = cloudInfoFromAAI;
151     }
152
153     public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
154         this.bbInputSetupUtils = bbInputSetupUtils;
155     }
156
157     public BBInputSetupMapperLayer getMapperLayer() {
158         return mapperLayer;
159     }
160
161     public void setMapperLayer(BBInputSetupMapperLayer mapperLayer) {
162         this.mapperLayer = mapperLayer;
163     }
164
165     /**
166      * This method is used for executing the building block.
167      *
168      * It will get the BB from the execution object by checking if the aLaCarte and homing is true.
169      *
170      * Then it will get the GBB and execute it.
171      *
172      * @param execution
173      * @throws Exception
174      * @return
175      */
176     @Override
177     public void execute(DelegateExecution execution) throws Exception {
178         try {
179             GeneralBuildingBlock outputBB = null;
180             ExecuteBuildingBlock executeBB = this.getExecuteBBFromExecution(execution);
181             String resourceId = executeBB.getResourceId();
182             String requestAction = executeBB.getRequestAction();
183             String vnfType = executeBB.getVnfType();
184             boolean aLaCarte = Boolean.TRUE.equals(executeBB.isaLaCarte());
185             boolean homing = Boolean.TRUE.equals(executeBB.isHoming());
186             Map<ResourceKey, String> lookupKeyMap = new HashMap<>();
187             outputBB = this.getGBB(executeBB, lookupKeyMap, requestAction, aLaCarte, resourceId, vnfType);
188             ObjectMapper mapper = new ObjectMapper();
189             mapper.enable(SerializationFeature.INDENT_OUTPUT);
190             logger.debug("GeneralBB: " + mapper.writeValueAsString(outputBB));
191
192             setHomingFlag(outputBB, homing, lookupKeyMap);
193
194             execution.setVariable(FLOW_VAR_NAME, executeBB.getBuildingBlock().getBpmnFlowName());
195             execution.setVariable(GBB_INPUT_VAR_NAME, outputBB);
196             execution.setVariable(LOOKUP_KEY_MAP_VAR_NAME, lookupKeyMap);
197
198             if (outputBB.getRequestContext().getIsHelm()) {
199                 execution.setVariable("isHelm", true);
200             } else {
201                 execution.setVariable("isHelm", false);
202             }
203
204             BuildingBlockExecution gBuildingBlockExecution = new DelegateExecutionImpl(execution);
205             execution.setVariable("gBuildingBlockExecution", gBuildingBlockExecution);
206             execution.setVariable("RetryCount", 1);
207             execution.setVariable("handlingCode", "Success");
208         } catch (Exception e) {
209             logger.error("Exception occurred", e);
210             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, e.getMessage());
211         }
212     }
213
214     protected void setHomingFlag(GeneralBuildingBlock outputBB, boolean homing, Map<ResourceKey, String> lookupKeyMap) {
215
216         if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null && homing && outputBB != null) {
217             for (GenericVnf vnf : outputBB.getCustomer().getServiceSubscription().getServiceInstances().get(0)
218                     .getVnfs()) {
219                 if (vnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
220                     vnf.setCallHoming(homing);
221                 }
222             }
223         }
224     }
225
226     protected ExecuteBuildingBlock getExecuteBBFromExecution(DelegateExecution execution) {
227         return (ExecuteBuildingBlock) execution.getVariable(EXECUTE_BB_VAR_NAME);
228     }
229
230     protected GeneralBuildingBlock getGBB(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap,
231             String requestAction, boolean aLaCarte, String resourceId, String vnfType) throws Exception {
232         String requestId = executeBB.getRequestId();
233         this.populateLookupKeyMapWithIds(executeBB.getWorkflowResourceIds(), lookupKeyMap);
234         RequestDetails requestDetails = executeBB.getRequestDetails();
235         if (requestDetails == null) {
236             requestDetails = bbInputSetupUtils.getRequestDetails(requestId);
237         }
238         if (requestDetails.getModelInfo() == null) {
239             return this.getGBBCM(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
240         } else {
241             ModelType modelType = requestDetails.getModelInfo().getModelType();
242             if (aLaCarte && modelType.equals(ModelType.service)) {
243                 return this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId);
244             } else if (aLaCarte && !modelType.equals(ModelType.service)) {
245                 return this.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId,
246                         vnfType);
247             } else {
248                 return this.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType);
249             }
250         }
251     }
252
253     protected void populateLookupKeyMapWithIds(WorkflowResourceIds workflowResourceIds,
254             Map<ResourceKey, String> lookupKeyMap) {
255         lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
256         lookupKeyMap.put(ResourceKey.NETWORK_ID, workflowResourceIds.getNetworkId());
257         lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, workflowResourceIds.getVnfId());
258         lookupKeyMap.put(ResourceKey.PNF, workflowResourceIds.getPnfId());
259         lookupKeyMap.put(ResourceKey.VF_MODULE_ID, workflowResourceIds.getVfModuleId());
260         lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, workflowResourceIds.getVolumeGroupId());
261         lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, workflowResourceIds.getConfigurationId());
262         lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, workflowResourceIds.getInstanceGroupId());
263         lookupKeyMap.put(ResourceKey.VNF_INSTANCE_NAME, workflowResourceIds.getVnfInstanceName());
264         lookupKeyMap.put(ResourceKey.VF_MODULE_INSTANCE_NAME, workflowResourceIds.getVfModuleInstanceName());
265     }
266
267     protected GeneralBuildingBlock getGBBALaCarteNonService(ExecuteBuildingBlock executeBB,
268             RequestDetails requestDetails, Map<ResourceKey, String> lookupKeyMap, String requestAction,
269             String resourceId, String vnfType) throws Exception {
270         String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
271         String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
272         org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
273         ServiceModel serviceModel = new ServiceModel();
274         Service service = null;
275         Service newService = null;
276         boolean isReplace = false;
277         if (serviceInstanceId != null) {
278             aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
279             if (aaiServiceInstance != null) {
280                 if (requestAction.equalsIgnoreCase("replaceInstance")
281                         || requestAction.equalsIgnoreCase("replaceInstanceRetainAssignments")) {
282                     RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
283                     if (relatedInstanceList != null) {
284                         for (RelatedInstanceList relatedInstList : relatedInstanceList) {
285                             RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
286                             if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) {
287                                 newService = bbInputSetupUtils.getCatalogServiceByModelUUID(
288                                         relatedInstance.getModelInfo().getModelVersionId());
289                                 isReplace = true;
290                             }
291                         }
292                     }
293                 }
294
295                 service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId());
296
297                 serviceModel.setNewService(newService);
298                 serviceModel.setCurrentService(service);
299
300                 if (service == null) {
301                     String message = String.format(
302                             "Related service instance model not found in MSO CatalogDB: model-version-id=%s",
303                             aaiServiceInstance.getModelVersionId());
304                     throw new ServiceModelNotFoundException(message);
305                 } else if (newService == null && isReplace) {
306                     String message = "Related service instance model in Request not found in MSO CatalogDB";
307                     throw new ServiceModelNotFoundException(message);
308                 }
309             } else {
310                 String message = String.format("Related service instance from AAI not found: service-instance-id=%s",
311                         serviceInstanceId);
312                 throw new NoServiceInstanceFoundException(message);
313             }
314         }
315
316         ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
317         if (isReplace) {
318             serviceInstance.setModelInfoServiceInstance(
319                     this.mapperLayer.mapCatalogServiceIntoServiceInstance(serviceModel.getNewService()));
320         } else {
321             serviceInstance.setModelInfoServiceInstance(
322                     this.mapperLayer.mapCatalogServiceIntoServiceInstance(serviceModel.getCurrentService()));
323         }
324         BBInputSetupParameter parameter = new BBInputSetupParameter.Builder().setRequestId(executeBB.getRequestId())
325                 .setRequestDetails(requestDetails).setService(service).setBbName(bbName)
326                 .setServiceInstance(serviceInstance).setLookupKeyMap(lookupKeyMap).setResourceId(resourceId)
327                 .setVnfType(vnfType).setKey(executeBB.getBuildingBlock().getKey())
328                 .setConfigurationResourceKeys(executeBB.getConfigurationResourceKeys()).setExecuteBB(executeBB)
329                 .setRequestAction(requestAction).setIsReplace(isReplace).setServiceModel(serviceModel).build();
330         this.populateObjectsOnAssignAndCreateFlows(parameter);
331         return this.populateGBBWithSIAndAdditionalInfo(parameter);
332     }
333
334     protected GeneralBuildingBlock getGBBCM(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
335             Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId) throws Exception {
336         ServiceInstance serviceInstance = new ServiceInstance();
337         String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
338         serviceInstance.setServiceInstanceId(serviceInstanceId);
339         Customer customer = new Customer();
340         List<GenericVnf> genericVnfs = serviceInstance.getVnfs();
341
342         String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
343         if (vnfId != null) {
344             org.onap.aai.domain.yang.GenericVnf aaiGenericVnf = bbInputSetupUtils.getAAIGenericVnf(vnfId);
345             GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnf);
346             genericVnfs.add(genericVnf);
347         }
348         String instanceGroupId = lookupKeyMap.get(ResourceKey.INSTANCE_GROUP_ID);
349         if (instanceGroupId != null && !instanceGroupId.isEmpty()) {
350             org.onap.aai.domain.yang.InstanceGroup aaiInstancegroup =
351                     bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
352             InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstancegroup);
353             instanceGroup.setOrchestrationStatus(OrchestrationStatus.INVENTORIED);
354
355             if (serviceInstanceId == null) {
356                 Optional<org.onap.aai.domain.yang.ServiceInstance> aaiServiceInstanceOpt =
357                         bbInputSetupUtils.getRelatedServiceInstanceFromInstanceGroup(instanceGroupId);
358                 if (aaiServiceInstanceOpt.isPresent()) {
359                     org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = aaiServiceInstanceOpt.get();
360                     serviceInstance = this.mapperLayer.mapAAIServiceInstanceIntoServiceInstance(aaiServiceInstance);
361                     WorkflowResourceIds workflowResourceIds = executeBB.getWorkflowResourceIds();
362                     workflowResourceIds.setServiceInstanceId(serviceInstance.getServiceInstanceId());
363                     lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId());
364                 } else {
365                     throw new NoServiceInstanceFoundException("Related ServiceInstance not found in A&AI.");
366                 }
367             }
368             RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList();
369             if (relatedInstanceList != null) {
370                 for (RelatedInstanceList relatedInstList : relatedInstanceList) {
371                     RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
372                     if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
373                         org.onap.aai.domain.yang.GenericVnf aaiVnf =
374                                 bbInputSetupUtils.getAAIGenericVnf(relatedInstance.getInstanceId());
375                         GenericVnf vnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiVnf);
376                         instanceGroup.getVnfs().add(vnf);
377                     }
378                 }
379             }
380
381             serviceInstance.getInstanceGroups().add(instanceGroup);
382             customer.setServiceSubscription(new ServiceSubscription());
383         }
384         BBInputSetupParameter parameter = new BBInputSetupParameter.Builder().setRequestDetails(requestDetails)
385                 .setServiceInstance(serviceInstance).setExecuteBB(executeBB).setRequestAction(requestAction)
386                 .setCustomer(customer).build();
387         return this.populateGBBWithSIAndAdditionalInfo(parameter);
388     }
389
390     protected void populateObjectsOnAssignAndCreateFlows(BBInputSetupParameter parameter) throws Exception {
391         parameter.setModelInfo(parameter.getRequestDetails().getModelInfo());
392         parameter.setInstanceName(parameter.getRequestDetails().getRequestInfo().getInstanceName());
393         parameter.setProductFamilyId(parameter.getRequestDetails().getRequestInfo().getProductFamilyId());
394         ModelType modelType = parameter.getModelInfo().getModelType();
395         parameter.setRelatedInstanceList(parameter.getRequestDetails().getRelatedInstanceList());
396
397         parameter.setPlatform(parameter.getRequestDetails().getPlatform());
398         parameter.setLineOfBusiness(parameter.getRequestDetails().getLineOfBusiness());
399         String applicationId = "";
400         if (parameter.getRequestDetails().getRequestInfo().getApplicationId() != null) {
401             applicationId = parameter.getRequestDetails().getRequestInfo().getApplicationId();
402             parameter.setApplicationId(applicationId);
403         }
404
405         if (modelType.equals(ModelType.network)) {
406             parameter.getLookupKeyMap().put(ResourceKey.NETWORK_ID, parameter.getResourceId());
407             this.populateL3Network(parameter);
408         } else if (modelType.equals(ModelType.vnf)) {
409             parameter.getLookupKeyMap().put(ResourceKey.GENERIC_VNF_ID, parameter.getResourceId());
410             this.populateGenericVnf(parameter);
411         } else if (modelType.equals(ModelType.volumeGroup) || (modelType.equals(ModelType.vfModule)
412                 && (parameter.getBbName().equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString())
413                         || parameter.getBbName().startsWith(CREATEVOLUME)))) {
414             parameter.getLookupKeyMap().put(ResourceKey.VOLUME_GROUP_ID, parameter.getResourceId());
415             this.populateVolumeGroup(parameter);
416         } else if (modelType.equals(ModelType.vfModule)) {
417             populateVfModuleOnAssignAndCreateFlows(parameter);
418         } else if (modelType.equals(ModelType.instanceGroup)) {
419             parameter.getLookupKeyMap().put(ResourceKey.INSTANCE_GROUP_ID, parameter.getResourceId());
420             this.populateInstanceGroup(parameter);
421         } else {
422             return;
423         }
424     }
425
426     protected void populateInstanceGroup(BBInputSetupParameter parameter) {
427         InstanceGroup instanceGroup = new InstanceGroup();
428         instanceGroup.setId(parameter.getInstanceGroupId());
429         instanceGroup.setInstanceGroupName(parameter.getInstanceName());
430         mapCatalogInstanceGroup(instanceGroup, parameter.getModelInfo(), parameter.getService());
431         parameter.getServiceInstance().getInstanceGroups().add(instanceGroup);
432     }
433
434     protected void populateVfModuleOnAssignAndCreateFlows(BBInputSetupParameter parameter) throws Exception {
435         if (parameter.getBbName().contains("Configuration")) {
436             parameter.setResourceId(parameter.getLookupKeyMap().get(ResourceKey.CONFIGURATION_ID));
437             parameter.getModelInfo().setModelCustomizationUuid(parameter.getConfigurationKey());
438             populateConfiguration(parameter);
439         } else {
440             parameter.getLookupKeyMap().put(ResourceKey.VF_MODULE_ID, parameter.getResourceId());
441             parameter.setCloudConfiguration(parameter.getRequestDetails().getCloudConfiguration());
442             this.populateVfModule(parameter);
443         }
444     }
445
446     protected void mapCatalogInstanceGroup(InstanceGroup instanceGroup, ModelInfo modelInfo, Service service) {
447         // @TODO: this will populate the instanceGroup model info.
448         // Dependent on MSO-5821 653458 US - MSO - Enhance Catalog DB Schema & Adapter
449         // to support VNF Groups
450     }
451
452     protected void populateConfiguration(BBInputSetupParameter parameter) {
453         Configuration configuration = null;
454         String replaceVnfModelCustomizationUUID = "";
455         if (parameter.getRelatedInstanceList() != null) {
456             for (RelatedInstanceList relatedInstList : parameter.getRelatedInstanceList()) {
457                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
458                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
459                     if (parameter.getIsReplace()) {
460                         replaceVnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
461                     }
462                 }
463             }
464         }
465         for (Configuration configurationTemp : parameter.getServiceInstance().getConfigurations()) {
466             if (parameter.getLookupKeyMap().get(ResourceKey.CONFIGURATION_ID) != null
467                     && configurationTemp.getConfigurationId()
468                             .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.CONFIGURATION_ID))) {
469                 configuration = configurationTemp;
470                 org.onap.aai.domain.yang.Configuration aaiConfiguration =
471                         bbInputSetupUtils.getAAIConfiguration(configuration.getConfigurationId());
472                 if (aaiConfiguration != null) {
473                     parameter.getModelInfo().setModelCustomizationUuid(aaiConfiguration.getModelCustomizationId());
474                 }
475             }
476         }
477         if (configuration == null
478                 && (parameter.getBbName().equalsIgnoreCase(AssignFlows.FABRIC_CONFIGURATION.toString())
479                         || parameter.getBbName().equalsIgnoreCase(AssignFlows.VRF_CONFIGURATION.toString()))) {
480             configuration = this.createConfiguration(parameter.getLookupKeyMap(), parameter.getInstanceName(),
481                     parameter.getResourceId());
482             parameter.getServiceInstance().getConfigurations().add(configuration);
483         }
484         if (configuration != null && parameter.getBbName().contains("Fabric")) {
485             Vnfc vnfc = getVnfcToConfiguration(parameter.getConfigurationResourceKeys().getVnfcName());
486             configuration.setVnfc(vnfc);
487             if (!parameter.getBbName().contains("Delete")) {
488                 if (parameter.getIsReplace()) {
489                     parameter.getConfigurationResourceKeys()
490                             .setVnfResourceCustomizationUUID(replaceVnfModelCustomizationUUID);
491                     mapCatalogConfiguration(configuration, parameter.getModelInfo(),
492                             parameter.getServiceModel().getNewService(), parameter.getConfigurationResourceKeys());
493                 } else {
494                     mapCatalogConfiguration(configuration, parameter.getModelInfo(),
495                             parameter.getServiceModel().getCurrentService(), parameter.getConfigurationResourceKeys());
496                 }
497             }
498         } else if (configuration != null && parameter.getBbName().contains("Vrf")) {
499             configuration.setModelInfoConfiguration(mapperLayer.mapCatalogConfigurationToConfiguration(
500                     findConfigurationResourceCustomization(parameter.getModelInfo(), parameter.getService()), null));
501             configuration.setConfigurationType(configuration.getModelInfoConfiguration().getConfigurationType());
502             configuration.setConfigurationSubType(configuration.getModelInfoConfiguration().getConfigurationRole());
503         }
504     }
505
506     protected Vnfc getVnfcToConfiguration(String vnfcName) {
507         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().vnfc(vnfcName));
508         Optional<org.onap.aai.domain.yang.Vnfc> vnfcOp =
509                 bbInputSetupUtils.getAAIResourceDepthOne(uri).asBean(org.onap.aai.domain.yang.Vnfc.class);
510         if (vnfcOp.isPresent()) {
511             org.onap.aai.domain.yang.Vnfc vnfcAAI = vnfcOp.get();
512             return this.mapperLayer.mapAAIVnfc(vnfcAAI);
513         } else {
514             return null;
515         }
516     }
517
518     protected Configuration createConfiguration(Map<ResourceKey, String> lookupKeyMap, String instanceName,
519             String resourceId) {
520         lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, resourceId);
521         Configuration configuration = new Configuration();
522         configuration.setConfigurationId(resourceId);
523         configuration.setConfigurationName(instanceName);
524         configuration.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
525         return configuration;
526     }
527
528     protected void mapCatalogConfiguration(Configuration configuration, ModelInfo modelInfo, Service service,
529             ConfigurationResourceKeys configurationResourceKeys) {
530         ConfigurationResourceCustomization configurationResourceCustomization =
531                 findConfigurationResourceCustomization(modelInfo, service);
532         CvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization =
533                 findVnfVfmoduleCvnfcConfigurationCustomization(service.getModelUUID(),
534                         configurationResourceKeys.getVfModuleCustomizationUUID(),
535                         configurationResourceKeys.getVnfResourceCustomizationUUID(),
536                         configurationResourceKeys.getCvnfcCustomizationUUID(), configurationResourceCustomization);
537         if (configurationResourceCustomization != null && vnfVfmoduleCvnfcConfigurationCustomization != null) {
538             configuration.setModelInfoConfiguration(this.mapperLayer.mapCatalogConfigurationToConfiguration(
539                     configurationResourceCustomization, vnfVfmoduleCvnfcConfigurationCustomization));
540         } else {
541             logger.debug("for Fabric configuration mapping by VF MODULE CUST UUID: "
542                     + configurationResourceKeys.getVfModuleCustomizationUUID());
543             vnfVfmoduleCvnfcConfigurationCustomization = findVnfVfmoduleCvnfcConfigurationCustomization(
544                     service.getModelUUID(), configurationResourceKeys.getVnfResourceCustomizationUUID(),
545                     configurationResourceKeys.getVfModuleCustomizationUUID(),
546                     configurationResourceKeys.getCvnfcCustomizationUUID());
547             if (vnfVfmoduleCvnfcConfigurationCustomization != null) {
548                 configuration.setModelInfoConfiguration(this.mapperLayer
549                         .mapCatalogConfigurationToConfiguration(vnfVfmoduleCvnfcConfigurationCustomization));
550             }
551         }
552     }
553
554     protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID,
555             String vfModuleCustomizationUUID, String vnfResourceCustomizationUUID, String cvnfcCustomizationUUID,
556             ConfigurationResourceCustomization configurationResourceCustomization) {
557         return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID,
558                 vfModuleCustomizationUUID, cvnfcCustomizationUUID);
559     }
560
561     protected ConfigurationResourceCustomization findConfigurationResourceCustomization(ModelInfo modelInfo,
562             Service service) {
563         for (ConfigurationResourceCustomization resourceCust : service.getConfigurationCustomizations()) {
564             if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
565                 return resourceCust;
566             }
567         }
568         return null;
569     }
570
571     protected CvnfcConfigurationCustomization findVnfVfmoduleCvnfcConfigurationCustomization(String serviceModelUUID,
572             String vnfResourceCustomizationUUID, String vfModuleCustomizationUUID, String cvnfcCustomizationUUID) {
573         return bbInputSetupUtils.getCvnfcConfigurationCustomization(serviceModelUUID, vnfResourceCustomizationUUID,
574                 vfModuleCustomizationUUID, cvnfcCustomizationUUID);
575     }
576
577     protected void populateVfModule(BBInputSetupParameter parameter) throws Exception {
578         String vnfModelCustomizationUUID = null;
579         String replaceVnfModelCustomizationUUID = null;
580         if (parameter.getRelatedInstanceList() != null) {
581             for (RelatedInstanceList relatedInstList : parameter.getRelatedInstanceList()) {
582                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
583                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
584                     if (parameter.getIsReplace()) {
585                         replaceVnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
586                     } else {
587                         vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
588                     }
589                 }
590                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.volumeGroup)) {
591                     parameter.getLookupKeyMap().put(ResourceKey.VOLUME_GROUP_ID, relatedInstance.getInstanceId());
592                 }
593             }
594         }
595         GenericVnf vnf = null;
596         for (GenericVnf tempVnf : parameter.getServiceInstance().getVnfs()) {
597             if (tempVnf.getVnfId().equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID))) {
598                 vnf = tempVnf;
599                 vnfModelCustomizationUUID =
600                         this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
601                 ModelInfo vnfModelInfo = new ModelInfo();
602                 if (parameter.getIsReplace()) {
603                     vnfModelInfo.setModelCustomizationUuid(replaceVnfModelCustomizationUUID);
604                     this.mapCatalogVnf(tempVnf, vnfModelInfo, parameter.getServiceModel().getNewService());
605                 } else {
606                     vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
607                     this.mapCatalogVnf(tempVnf, vnfModelInfo, parameter.getServiceModel().getCurrentService());
608                 }
609                 Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(tempVnf, parameter.getModelInfo(),
610                         parameter.getCloudConfiguration().getCloudOwner(),
611                         parameter.getCloudConfiguration().getLcpCloudRegionId(), parameter.getLookupKeyMap());
612                 if (volumeGroupIdOp.isPresent()) {
613                     parameter.getLookupKeyMap().put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
614                 }
615                 break;
616             }
617         }
618         if (vnf != null) {
619             VfModule vfModule = null;
620             for (VfModule vfModuleTemp : vnf.getVfModules()) {
621                 if (parameter.getLookupKeyMap().get(ResourceKey.VF_MODULE_ID) != null && vfModuleTemp.getVfModuleId()
622                         .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.VF_MODULE_ID))) {
623                     vfModule = vfModuleTemp;
624                 }
625                 String vfModuleCustId = bbInputSetupUtils.getAAIVfModule(vnf.getVnfId(), vfModuleTemp.getVfModuleId())
626                         .getModelCustomizationId();
627                 ModelInfo modelInfoVfModule = new ModelInfo();
628                 modelInfoVfModule.setModelCustomizationId(vfModuleCustId);
629                 if (parameter.getIsReplace() && parameter.getLookupKeyMap().get(ResourceKey.VF_MODULE_ID) != null
630                         && vfModuleTemp.getVfModuleId()
631                                 .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.VF_MODULE_ID))) {
632                     mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, parameter.getServiceModel().getNewService(),
633                             replaceVnfModelCustomizationUUID);
634                 } else {
635                     mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, parameter.getServiceModel().getCurrentService(),
636                             vnfModelCustomizationUUID);
637                 }
638             }
639             if (vfModule == null && parameter.getBbName().equalsIgnoreCase(AssignFlows.VF_MODULE.toString())) {
640                 vfModule = createVfModule(parameter.getLookupKeyMap(), parameter.getResourceId(),
641                         parameter.getInstanceName(), parameter.getInstanceParams());
642                 vnf.getVfModules().add(vfModule);
643                 if (parameter.getIsReplace()) {
644                     mapCatalogVfModule(vfModule, parameter.getModelInfo(), parameter.getServiceModel().getNewService(),
645                             replaceVnfModelCustomizationUUID);
646                 } else {
647                     mapCatalogVfModule(vfModule, parameter.getModelInfo(),
648                             parameter.getServiceModel().getCurrentService(), vnfModelCustomizationUUID);
649                 }
650             }
651             if (vfModule != null && vfModule.getModelInfoVfModule() != null
652                     && vfModule.getModelInfoVfModule().getModelName() != null
653                     && vfModule.getModelInfoVfModule().getModelName().contains("helm")) {
654                 parameter.setIsHelm(true);
655             }
656         } else {
657             logger.debug("Related VNF instance Id not found: {}",
658                     parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID));
659             throw new Exception("Could not find relevant information for related VNF");
660         }
661     }
662
663     protected Optional<String> getVolumeGroupIdRelatedToVfModule(GenericVnf vnf, ModelInfo modelInfo, String cloudOwner,
664             String cloudRegionId, Map<ResourceKey, String> lookupKeyMap) {
665         if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) == null) {
666             for (VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
667                 String volumeGroupCustId =
668                         bbInputSetupUtils.getAAIVolumeGroup(cloudOwner, cloudRegionId, volumeGroup.getVolumeGroupId())
669                                 .getModelCustomizationId();
670                 if (modelInfo.getModelCustomizationId().equalsIgnoreCase(volumeGroupCustId)) {
671                     logger.debug("Found volume group for vfModule: " + volumeGroup.getVolumeGroupId());
672                     return Optional.of(volumeGroup.getVolumeGroupId());
673                 }
674             }
675         }
676         return Optional.empty();
677     }
678
679     protected void mapCatalogVfModule(VfModule vfModule, ModelInfo modelInfo, Service service,
680             String vnfModelCustomizationUUID) {
681         if (modelInfo.getModelCustomizationUuid() != null) {
682             modelInfo.setModelCustomizationId(modelInfo.getModelCustomizationUuid());
683         }
684         VnfResourceCustomization vnfResourceCustomization = null;
685         for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
686             if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
687                 vnfResourceCustomization = resourceCust;
688                 break;
689             }
690         }
691         VfModuleCustomization vfResourceCustomization = null;
692         if (vnfResourceCustomization != null) {
693             vfResourceCustomization = vnfResourceCustomization.getVfModuleCustomizations().stream() // Convert to steam
694                     .filter(x -> modelInfo.getModelCustomizationId().equalsIgnoreCase(x.getModelCustomizationUUID()))// find
695                     // what
696                     // we
697                     // want
698                     .findAny() // If 'findAny' then return found
699                     .orElse(null);
700         }
701         if (vfResourceCustomization == null) {
702             vfResourceCustomization = bbInputSetupUtils
703                     .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
704         }
705         if (vfResourceCustomization != null) {
706             vfModule.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
707         }
708     }
709
710     protected VfModule createVfModule(Map<ResourceKey, String> lookupKeyMap, String vfModuleId, String instanceName,
711             List<Map<String, String>> instanceParams) {
712         lookupKeyMap.put(ResourceKey.VF_MODULE_ID, vfModuleId);
713         VfModule vfModule = new VfModule();
714         vfModule.setVfModuleId(vfModuleId);
715         vfModule.setVfModuleName(instanceName);
716         vfModule.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
717         if (instanceParams != null) {
718             for (Map<String, String> params : instanceParams) {
719                 vfModule.getCloudParams().putAll(params);
720             }
721         }
722         return vfModule;
723     }
724
725     protected void populateVolumeGroup(BBInputSetupParameter parameter) throws Exception {
726         String replaceVnfModelCustomizationUUID = null;
727         VolumeGroup volumeGroup = null;
728         GenericVnf vnf = null;
729         String vnfModelCustomizationUUID = null;
730         String generatedVnfType = parameter.getVnfType();
731         if (generatedVnfType == null || generatedVnfType.isEmpty()) {
732             generatedVnfType =
733                     parameter.getService().getModelName() + "/" + parameter.getModelInfo().getModelCustomizationName();
734         }
735         if (parameter.getRelatedInstanceList() != null) {
736             for (RelatedInstanceList relatedInstList : parameter.getRelatedInstanceList()) {
737                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
738                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
739                     if (parameter.getIsReplace()) {
740                         replaceVnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
741                     } else {
742                         vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
743                     }
744                     break;
745                 }
746             }
747         }
748         for (GenericVnf tempVnf : parameter.getServiceInstance().getVnfs()) {
749             if (tempVnf.getVnfId().equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID))) {
750                 vnf = tempVnf;
751                 vnfModelCustomizationUUID =
752                         bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
753                 ModelInfo vnfModelInfo = new ModelInfo();
754                 if (parameter.getIsReplace()) {
755                     vnfModelInfo.setModelCustomizationUuid(replaceVnfModelCustomizationUUID);
756                     mapCatalogVnf(tempVnf, vnfModelInfo, parameter.getServiceModel().getNewService());
757                 } else {
758                     vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
759                     mapCatalogVnf(tempVnf, vnfModelInfo, parameter.getServiceModel().getCurrentService());
760                 }
761                 break;
762             }
763         }
764         if (vnf != null && vnfModelCustomizationUUID != null) {
765             for (VolumeGroup volumeGroupTemp : vnf.getVolumeGroups()) {
766                 if (parameter.getLookupKeyMap().get(ResourceKey.VOLUME_GROUP_ID) != null
767                         && volumeGroupTemp.getVolumeGroupId()
768                                 .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.VOLUME_GROUP_ID))) {
769                     volumeGroup = volumeGroupTemp;
770                     if (volumeGroup.getModelInfoVfModule() == null) {
771                         throw new Exception(
772                                 "ModelInfoVfModule is null for VolumeGroup: " + volumeGroup.getVolumeGroupId());
773                     }
774                     String volumeGroupCustId = volumeGroup.getModelInfoVfModule().getModelCustomizationUUID();
775                     ModelInfo modelInfoVolumeGroup = new ModelInfo();
776                     modelInfoVolumeGroup.setModelCustomizationId(volumeGroupCustId);
777                     if (parameter.getIsReplace() && parameter.getLookupKeyMap().get(ResourceKey.VOLUME_GROUP_ID) != null
778                             && volumeGroupTemp.getVolumeGroupId()
779                                     .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.VOLUME_GROUP_ID))) {
780                         mapCatalogVolumeGroup(volumeGroupTemp, modelInfoVolumeGroup,
781                                 parameter.getServiceModel().getNewService(), replaceVnfModelCustomizationUUID);
782                     } else {
783                         mapCatalogVolumeGroup(volumeGroupTemp, modelInfoVolumeGroup,
784                                 parameter.getServiceModel().getCurrentService(), vnfModelCustomizationUUID);
785                     }
786                     break;
787                 }
788             }
789             if (volumeGroup == null && parameter.getBbName().equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString())) {
790                 volumeGroup = createVolumeGroup(parameter.getLookupKeyMap(), parameter.getResourceId(),
791                         parameter.getInstanceName(), generatedVnfType, parameter.getInstanceParams());
792                 vnf.getVolumeGroups().add(volumeGroup);
793                 if (parameter.getIsReplace()) {
794                     if (parameter.getExecuteBB().getOldVolumeGroupName() != null
795                             && !parameter.getExecuteBB().getOldVolumeGroupName().isEmpty()) {
796                         volumeGroup.setVolumeGroupName(parameter.getExecuteBB().getOldVolumeGroupName());
797                     }
798                     mapCatalogVolumeGroup(volumeGroup, parameter.getModelInfo(),
799                             parameter.getServiceModel().getNewService(), replaceVnfModelCustomizationUUID);
800                 } else {
801                     mapCatalogVolumeGroup(volumeGroup, parameter.getModelInfo(),
802                             parameter.getServiceModel().getCurrentService(), vnfModelCustomizationUUID);
803                 }
804             }
805         } else {
806             logger.debug("Related VNF instance Id not found: {}",
807                     parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID));
808             throw new Exception("Could not find relevant information for related VNF");
809         }
810     }
811
812     protected VolumeGroup createVolumeGroup(Map<ResourceKey, String> lookupKeyMap, String volumeGroupId,
813             String instanceName, String vnfType, List<Map<String, String>> instanceParams) {
814         lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId);
815         VolumeGroup volumeGroup = new VolumeGroup();
816         volumeGroup.setVolumeGroupId(volumeGroupId);
817         volumeGroup.setVolumeGroupName(instanceName);
818         volumeGroup.setVnfType(vnfType);
819         volumeGroup.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
820         if (instanceParams != null) {
821             for (Map<String, String> params : instanceParams) {
822                 volumeGroup.getCloudParams().putAll(params);
823             }
824         }
825         return volumeGroup;
826     }
827
828     protected void mapCatalogVolumeGroup(VolumeGroup volumeGroup, ModelInfo modelInfo, Service service,
829             String vnfModelCustomizationUUID) {
830         VfModuleCustomization vfResourceCustomization =
831                 getVfResourceCustomization(modelInfo, service, vnfModelCustomizationUUID);
832         if (vfResourceCustomization != null) {
833             volumeGroup.setModelInfoVfModule(this.mapperLayer.mapCatalogVfModuleToVfModule(vfResourceCustomization));
834         }
835     }
836
837     protected VfModuleCustomization getVfResourceCustomization(ModelInfo modelInfo, Service service,
838             String vnfModelCustomizationUUID) {
839         VnfResourceCustomization vnfResourceCustomization = null;
840         for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
841             if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(vnfModelCustomizationUUID)) {
842                 vnfResourceCustomization = resourceCust;
843                 break;
844             }
845         }
846         if (vnfResourceCustomization != null) {
847             for (VfModuleCustomization vfResourceCust : vnfResourceCustomization.getVfModuleCustomizations()) {
848                 if (vfResourceCust.getModelCustomizationUUID()
849                         .equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
850                     return vfResourceCust;
851                 }
852             }
853
854         }
855         return null;
856     }
857
858     protected void populateGenericVnf(BBInputSetupParameter parameter) {
859         GenericVnf vnf = null;
860         ModelInfo instanceGroupModelInfo = null;
861         String instanceGroupId = null;
862         String generatedVnfType = parameter.getVnfType();
863         String replaceVnfModelCustomizationUUID = null;
864         if (generatedVnfType == null || generatedVnfType.isEmpty()) {
865             generatedVnfType =
866                     parameter.getService().getModelName() + "/" + parameter.getModelInfo().getModelCustomizationName();
867         }
868         if (parameter.getRelatedInstanceList() != null) {
869             for (RelatedInstanceList relatedInstList : parameter.getRelatedInstanceList()) {
870                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
871                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.networkInstanceGroup)) {
872                     instanceGroupModelInfo = relatedInstance.getModelInfo();
873                     instanceGroupId = relatedInstance.getInstanceId();
874                 }
875                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf) && parameter.getIsReplace()) {
876                     replaceVnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
877                 }
878             }
879         }
880         for (GenericVnf vnfTemp : parameter.getServiceInstance().getVnfs()) {
881             if (parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID) != null && vnfTemp.getVnfId()
882                     .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID))) {
883                 String vnfModelCustId =
884                         bbInputSetupUtils.getAAIGenericVnf(vnfTemp.getVnfId()).getModelCustomizationId();
885                 if (parameter.getIsReplace() && replaceVnfModelCustomizationUUID != null && vnfTemp.getVnfId()
886                         .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.GENERIC_VNF_ID))) {
887                     parameter.getModelInfo().setModelCustomizationUuid(replaceVnfModelCustomizationUUID);
888                 } else {
889                     parameter.getModelInfo().setModelCustomizationUuid(vnfModelCustId);
890                 }
891                 vnf = vnfTemp;
892                 break;
893             }
894         }
895         if (vnf == null && parameter.getBbName().equalsIgnoreCase(AssignFlows.VNF.toString())) {
896             vnf = createGenericVnf(parameter.getLookupKeyMap(), parameter.getInstanceName(), parameter.getPlatform(),
897                     parameter.getLineOfBusiness(), parameter.getResourceId(), generatedVnfType,
898                     parameter.getInstanceParams(), parameter.getProductFamilyId(), parameter.getApplicationId());
899             parameter.getServiceInstance().getVnfs().add(vnf);
900             mapVnfcCollectionInstanceGroup(vnf, parameter.getModelInfo(), parameter.getService());
901         }
902         if (vnf != null) {
903             mapCatalogVnf(vnf, parameter.getModelInfo(), parameter.getService());
904             if (instanceGroupId != null && instanceGroupModelInfo != null
905                     && instanceGroupModelInfo.getModelType().equals(ModelType.networkInstanceGroup)
906                     && !instanceGroupInList(vnf, instanceGroupId)) {
907                 mapNetworkCollectionInstanceGroup(vnf, instanceGroupId);
908             }
909         }
910     }
911
912     protected boolean instanceGroupInList(GenericVnf vnf, String instanceGroupId) {
913         for (InstanceGroup instanceGroup : vnf.getInstanceGroups()) {
914             if (instanceGroup.getId() != null && instanceGroup.getId().equalsIgnoreCase(instanceGroupId)) {
915                 return true;
916             }
917         }
918         return false;
919     }
920
921     protected void mapVnfcCollectionInstanceGroup(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
922         VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
923         if (vnfResourceCustomization != null) {
924             List<VnfcInstanceGroupCustomization> vnfcInstanceGroups =
925                     vnfResourceCustomization.getVnfcInstanceGroupCustomizations();
926             for (VnfcInstanceGroupCustomization vnfcInstanceGroupCust : vnfcInstanceGroups) {
927                 InstanceGroup instanceGroup = this.createInstanceGroup();
928                 org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = bbInputSetupUtils
929                         .getCatalogInstanceGroup(vnfcInstanceGroupCust.getInstanceGroup().getModelUUID());
930                 instanceGroup.setModelInfoInstanceGroup(
931                         this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null, catalogInstanceGroup));
932                 instanceGroup.getModelInfoInstanceGroup().setFunction(vnfcInstanceGroupCust.getFunction());
933                 instanceGroup.getModelInfoInstanceGroup().setDescription(vnfcInstanceGroupCust.getDescription());
934                 genericVnf.getInstanceGroups().add(instanceGroup);
935             }
936         }
937     }
938
939     protected void mapNetworkCollectionInstanceGroup(GenericVnf genericVnf, String instanceGroupId) {
940         org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup =
941                 bbInputSetupUtils.getAAIInstanceGroup(instanceGroupId);
942         InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
943         instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null,
944                 this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
945         genericVnf.getInstanceGroups().add(instanceGroup);
946     }
947
948     protected GenericVnf createGenericVnf(Map<ResourceKey, String> lookupKeyMap, String instanceName,
949             org.onap.so.serviceinstancebeans.Platform platform,
950             org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, String vnfId, String vnfType,
951             List<Map<String, String>> instanceParams, String productFamilyId, String applicationId) {
952         lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId);
953         GenericVnf genericVnf = new GenericVnf();
954         genericVnf.setVnfId(vnfId);
955         genericVnf.setVnfName(instanceName);
956         genericVnf.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
957         genericVnf.setVnfType(vnfType);
958         genericVnf.setProvStatus(PREPROV);
959         genericVnf.setServiceId(productFamilyId);
960         genericVnf.setApplicationId(applicationId);
961         if (platform != null) {
962             genericVnf.setPlatform(this.mapperLayer.mapRequestPlatform(platform));
963         }
964         if (lineOfBusiness != null) {
965             genericVnf.setLineOfBusiness(this.mapperLayer.mapRequestLineOfBusiness(lineOfBusiness));
966         }
967         if (instanceParams != null) {
968             for (Map<String, String> params : instanceParams) {
969                 genericVnf.getCloudParams().putAll(params);
970             }
971         }
972         return genericVnf;
973     }
974
975     protected void mapCatalogVnf(GenericVnf genericVnf, ModelInfo modelInfo, Service service) {
976         VnfResourceCustomization vnfResourceCustomization = getVnfResourceCustomizationFromService(modelInfo, service);
977         if (vnfResourceCustomization != null) {
978             genericVnf.setModelInfoGenericVnf(this.mapperLayer.mapCatalogVnfToVnf(vnfResourceCustomization));
979         }
980     }
981
982     protected VnfResourceCustomization getVnfResourceCustomizationFromService(ModelInfo modelInfo, Service service) {
983         VnfResourceCustomization vnfResourceCustomization = null;
984         for (VnfResourceCustomization resourceCust : service.getVnfCustomizations()) {
985             if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
986                 vnfResourceCustomization = resourceCust;
987                 break;
988             }
989         }
990         return vnfResourceCustomization;
991     }
992
993     protected void populateL3Network(BBInputSetupParameter parameter) {
994         L3Network network = null;
995         for (L3Network networkTemp : parameter.getServiceInstance().getNetworks()) {
996             if (parameter.getLookupKeyMap().get(ResourceKey.NETWORK_ID) != null && networkTemp.getNetworkId()
997                     .equalsIgnoreCase(parameter.getLookupKeyMap().get(ResourceKey.NETWORK_ID))) {
998                 network = networkTemp;
999                 break;
1000             }
1001         }
1002         if (network == null && (parameter.getBbName().equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
1003                 || parameter.getBbName().equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
1004             network = createNetwork(parameter.getLookupKeyMap(), parameter.getInstanceName(), parameter.getResourceId(),
1005                     parameter.getInstanceParams(), parameter);
1006             parameter.getServiceInstance().getNetworks().add(network);
1007         }
1008         if (network != null) {
1009             mapCatalogNetwork(network, parameter.getModelInfo(), parameter.getService());
1010         }
1011     }
1012
1013     protected L3Network createNetwork(Map<ResourceKey, String> lookupKeyMap, String instanceName, String networkId,
1014             List<Map<String, String>> instanceParams, BBInputSetupParameter parameter) {
1015         lookupKeyMap.put(ResourceKey.NETWORK_ID, networkId);
1016         L3Network network = new L3Network();
1017         network.setNetworkId(networkId);
1018         network.setNetworkName(instanceName);
1019         network.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
1020         if (parameter != null) {
1021             if (parameter.getLineOfBusiness() != null) {
1022                 network.setLineOfBusiness(this.mapperLayer.mapRequestLineOfBusiness(parameter.getLineOfBusiness()));
1023             }
1024             if (parameter.getLineOfBusiness() != null) {
1025                 network.setPlatform(this.mapperLayer.mapRequestPlatform(parameter.getPlatform()));
1026             }
1027         }
1028         if (instanceParams != null) {
1029             for (Map<String, String> params : instanceParams) {
1030                 network.getCloudParams().putAll(params);
1031             }
1032         }
1033         return network;
1034     }
1035
1036     protected void mapCatalogNetwork(L3Network network, ModelInfo modelInfo, Service service) {
1037         NetworkResourceCustomization networkResourceCustomization = null;
1038         for (NetworkResourceCustomization resourceCust : service.getNetworkCustomizations()) {
1039             if (resourceCust.getModelCustomizationUUID().equalsIgnoreCase(modelInfo.getModelCustomizationUuid())) {
1040                 networkResourceCustomization = resourceCust;
1041                 break;
1042             }
1043         }
1044         if (networkResourceCustomization != null) {
1045             network.setModelInfoNetwork(this.mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
1046         }
1047     }
1048
1049     protected GeneralBuildingBlock getGBBALaCarteService(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
1050             Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId) throws Exception {
1051         Customer customer = getCustomerAndServiceSubscription(requestDetails, resourceId);
1052         if (customer != null) {
1053             Project project = null;
1054             OwningEntity owningEntity = null;
1055
1056             if (requestDetails.getProject() != null)
1057                 project = mapperLayer.mapRequestProject(requestDetails.getProject());
1058             if (requestDetails.getOwningEntity() != null)
1059                 owningEntity = mapperLayer.mapRequestOwningEntity(requestDetails.getOwningEntity());
1060
1061             String modelVersionId = requestDetails.getModelInfo().getModelVersionId();
1062
1063             if (ModelType.vnf == requestDetails.getModelInfo().getModelType()) {
1064                 for (RelatedInstanceList relatedInstanceList : requestDetails.getRelatedInstanceList()) {
1065                     if (ModelType.service == relatedInstanceList.getRelatedInstance().getModelInfo().getModelType()) {
1066                         modelVersionId = relatedInstanceList.getRelatedInstance().getModelInfo().getModelVersionId();
1067                         break;
1068                     }
1069                 }
1070             }
1071
1072             Service service = bbInputSetupUtils.getCatalogServiceByModelUUID(modelVersionId);
1073             if (service == null) {
1074                 service = bbInputSetupUtils.getCatalogServiceByModelVersionAndModelInvariantUUID(
1075                         requestDetails.getModelInfo().getModelVersion(),
1076                         requestDetails.getModelInfo().getModelInvariantId());
1077                 if (service == null) {
1078                     throw new Exception("Could not find service for model version Id: "
1079                             + requestDetails.getModelInfo().getModelVersionId() + " and for model invariant Id: "
1080                             + requestDetails.getModelInfo().getModelInvariantId());
1081                 }
1082             }
1083             ServiceInstance serviceInstance = this.getALaCarteServiceInstance(service, requestDetails, customer,
1084                     project, owningEntity, lookupKeyMap, resourceId, Boolean.TRUE.equals(executeBB.isaLaCarte()),
1085                     executeBB.getBuildingBlock().getBpmnFlowName());
1086             BBInputSetupParameter parameter = new BBInputSetupParameter.Builder().setRequestDetails(requestDetails)
1087                     .setServiceInstance(serviceInstance).setExecuteBB(executeBB).setRequestAction(requestAction)
1088                     .setCustomer(customer).build();
1089             return this.populateGBBWithSIAndAdditionalInfo(parameter);
1090         } else {
1091             throw new Exception("Could not find customer");
1092         }
1093     }
1094
1095     protected Customer getCustomerAndServiceSubscription(RequestDetails requestDetails, String resourceId) {
1096         Customer customer;
1097         if (requestDetails.getSubscriberInfo() != null) {
1098             customer = this.getCustomerFromRequest(requestDetails);
1099         } else {
1100             customer = this.getCustomerFromURI(resourceId);
1101         }
1102         if (customer != null) {
1103             ServiceSubscription serviceSubscription = null;
1104             serviceSubscription = getServiceSubscription(requestDetails, customer);
1105             if (serviceSubscription == null) {
1106                 serviceSubscription = getServiceSubscriptionFromURI(resourceId, customer);
1107             }
1108             customer.setServiceSubscription(serviceSubscription);
1109             return customer;
1110         } else {
1111             return null;
1112         }
1113     }
1114
1115     protected ServiceSubscription getServiceSubscriptionFromURI(String resourceId, Customer customer) {
1116         Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
1117         String subscriptionServiceType =
1118                 uriKeys.get(AAIFluentTypeBuilder.Types.SERVICE_SUBSCRIPTION.getUriParams().serviceType);
1119         org.onap.aai.domain.yang.ServiceSubscription serviceSubscriptionAAI =
1120                 bbInputSetupUtils.getAAIServiceSubscription(customer.getGlobalCustomerId(), subscriptionServiceType);
1121         if (serviceSubscriptionAAI != null) {
1122             return mapperLayer.mapAAIServiceSubscription(serviceSubscriptionAAI);
1123         } else {
1124             return null;
1125         }
1126     }
1127
1128     protected Customer getCustomerFromURI(String resourceId) {
1129         Map<String, String> uriKeys = bbInputSetupUtils.getURIKeysFromServiceInstance(resourceId);
1130         String globalCustomerId = uriKeys.get(AAIFluentTypeBuilder.Types.CUSTOMER.getUriParams().globalCustomerId);
1131         org.onap.aai.domain.yang.Customer customerAAI = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
1132         if (customerAAI != null) {
1133             return mapperLayer.mapAAICustomer(customerAAI);
1134         } else {
1135             return null;
1136         }
1137     }
1138
1139     protected GeneralBuildingBlock populateGBBWithSIAndAdditionalInfo(BBInputSetupParameter parameter)
1140             throws Exception {
1141         GeneralBuildingBlock outputBB = new GeneralBuildingBlock();
1142         OrchestrationContext orchContext = mapperLayer.mapOrchestrationContext(parameter.getRequestDetails());
1143         RequestContext requestContext = mapperLayer.mapRequestContext(parameter.getRequestDetails());
1144         requestContext.setAction(parameter.getRequestAction());
1145         requestContext.setMsoRequestId(parameter.getExecuteBB().getRequestId());
1146         requestContext.setIsHelm(parameter.getIsHelm());
1147         org.onap.aai.domain.yang.CloudRegion aaiCloudRegion =
1148                 bbInputSetupUtils.getCloudRegion(parameter.getRequestDetails().getCloudConfiguration());
1149         CloudRegion cloudRegion =
1150                 mapperLayer.mapCloudRegion(parameter.getRequestDetails().getCloudConfiguration(), aaiCloudRegion);
1151         Tenant tenant = getTenant(parameter.getRequestDetails().getCloudConfiguration(), aaiCloudRegion);
1152         outputBB.setOrchContext(orchContext);
1153         outputBB.setRequestContext(requestContext);
1154         outputBB.setCloudRegion(cloudRegion);
1155         outputBB.setTenant(tenant);
1156         Customer customer = parameter.getCustomer();
1157         if (customer == null) {
1158             Map<String, String> uriKeys = bbInputSetupUtils
1159                     .getURIKeysFromServiceInstance(parameter.getServiceInstance().getServiceInstanceId());
1160             String globalCustomerId = uriKeys.get(AAIFluentTypeBuilder.Types.CUSTOMER.getUriParams().globalCustomerId);
1161             String subscriptionServiceType =
1162                     uriKeys.get(AAIFluentTypeBuilder.Types.SERVICE_SUBSCRIPTION.getUriParams().serviceType);
1163             customer = mapCustomer(globalCustomerId, subscriptionServiceType);
1164         }
1165         outputBB.setServiceInstance(parameter.getServiceInstance());
1166         if (customer.getServiceSubscription() != null) {
1167             customer.getServiceSubscription().getServiceInstances().add(parameter.getServiceInstance());
1168         }
1169         outputBB.setCustomer(customer);
1170         return outputBB;
1171     }
1172
1173     protected Tenant getTenant(CloudConfiguration cloudConfiguration,
1174             org.onap.aai.domain.yang.CloudRegion aaiCloudRegion) throws Exception {
1175         Tenant tenant = new Tenant();
1176         if (cloudConfiguration != null && cloudConfiguration.getTenantId() != null && aaiCloudRegion != null
1177                 && aaiCloudRegion.getTenants() != null) {
1178             for (org.onap.aai.domain.yang.Tenant aaiTenant : aaiCloudRegion.getTenants().getTenant()) {
1179                 if (aaiTenant.getTenantId().equalsIgnoreCase(cloudConfiguration.getTenantId())) {
1180                     tenant = mapperLayer.mapTenant(aaiTenant);
1181                 }
1182             }
1183             if (tenant.getTenantId() == null || tenant.getTenantName() == null) {
1184                 throw new Exception("Invalid tenant information retrieved: tenantId = " + tenant.getTenantId()
1185                         + " tenantName = " + tenant.getTenantName());
1186             }
1187         }
1188         return tenant;
1189     }
1190
1191     protected ServiceSubscription getServiceSubscription(RequestDetails requestDetails, Customer customer) {
1192         org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription =
1193                 bbInputSetupUtils.getAAIServiceSubscription(customer.getGlobalCustomerId(),
1194                         requestDetails.getRequestParameters().getSubscriptionServiceType());
1195         if (aaiServiceSubscription != null) {
1196             return mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
1197         } else {
1198             return null;
1199         }
1200     }
1201
1202     protected Customer getCustomerFromRequest(RequestDetails requestDetails) {
1203         org.onap.aai.domain.yang.Customer aaiCustomer =
1204                 bbInputSetupUtils.getAAICustomer(requestDetails.getSubscriberInfo().getGlobalSubscriberId());
1205         if (aaiCustomer != null) {
1206             return mapperLayer.mapAAICustomer(aaiCustomer);
1207         } else {
1208             return null;
1209         }
1210     }
1211
1212     protected ServiceInstance getALaCarteServiceInstance(Service service, RequestDetails requestDetails,
1213             Customer customer, Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap,
1214             String serviceInstanceId, boolean aLaCarte, String bbName) throws Exception {
1215         ServiceInstance serviceInstance = this.getServiceInstanceHelper(requestDetails, customer, project, owningEntity,
1216                 lookupKeyMap, serviceInstanceId, aLaCarte, service, bbName);
1217         org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
1218         if (customer != null && customer.getServiceSubscription() != null) {
1219             serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
1220                     customer.getServiceSubscription().getServiceType(), serviceInstanceId);
1221         } else {
1222             serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
1223         }
1224         if (serviceInstanceAAI != null
1225                 && !serviceInstanceAAI.getModelVersionId().equalsIgnoreCase(service.getModelUUID())) {
1226             Service tempService =
1227                     this.bbInputSetupUtils.getCatalogServiceByModelUUID(serviceInstanceAAI.getModelVersionId());
1228             if (tempService != null) {
1229                 serviceInstance
1230                         .setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(tempService));
1231                 return serviceInstance;
1232             } else {
1233                 throw new Exception(
1234                         "Could not find model of existing SI. Service Instance in AAI already exists with different model version id: "
1235                                 + serviceInstanceAAI.getModelVersionId());
1236             }
1237         }
1238         serviceInstance.setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(service));
1239         return serviceInstance;
1240     }
1241
1242     protected GeneralBuildingBlock getGBBMacro(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
1243             Map<ResourceKey, String> lookupKeyMap, String requestAction, String resourceId, String vnfType)
1244             throws Exception {
1245         String bbName = executeBB.getBuildingBlock().getBpmnFlowName();
1246         String key = executeBB.getBuildingBlock().getKey();
1247
1248         if (requestAction.equalsIgnoreCase("deleteInstance") || requestAction.equalsIgnoreCase("unassignInstance")
1249                 || requestAction.equalsIgnoreCase("activateInstance")
1250                 || requestAction.equalsIgnoreCase("activateFabricConfiguration")
1251                 || requestAction.equalsIgnoreCase("recreateInstance")
1252                 || requestAction.equalsIgnoreCase("replaceInstance")
1253                 || requestAction.equalsIgnoreCase("upgradeInstance")) {
1254             return getGBBMacroExistingService(executeBB, lookupKeyMap, bbName, requestAction,
1255                     requestDetails.getCloudConfiguration());
1256         }
1257
1258         String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
1259         GeneralBuildingBlock gBB =
1260                 this.getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, serviceInstanceId);
1261         RequestParameters requestParams = requestDetails.getRequestParameters();
1262         Service service = null;
1263         if (gBB != null && gBB.getServiceInstance() != null
1264                 && gBB.getServiceInstance().getModelInfoServiceInstance() != null
1265                 && gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid() != null) {
1266             service = bbInputSetupUtils.getCatalogServiceByModelUUID(
1267                     gBB.getServiceInstance().getModelInfoServiceInstance().getModelUuid());
1268         } else {
1269             throw new Exception("Could not get service instance for macro request");
1270         }
1271         if (requestParams != null && requestParams.getUserParams() != null) {
1272             for (Map<String, Object> userParams : requestParams.getUserParams()) {
1273                 if (userParams.containsKey("service")) {
1274                     String input = mapper.writeValueAsString(userParams.get("service"));
1275                     return getGBBMacroUserParams(executeBB, requestDetails, lookupKeyMap, vnfType, bbName, key, gBB,
1276                             requestParams, service, input);
1277                 }
1278             }
1279         }
1280         if (requestAction.equalsIgnoreCase("deactivateInstance")) {
1281             return gBB;
1282         } else if (requestAction.equalsIgnoreCase("createInstance")) {
1283             return getGBBMacroNoUserParamsCreate(executeBB, lookupKeyMap, bbName, key, gBB, service);
1284         } else {
1285             throw new IllegalArgumentException(
1286                     "No user params on requestAction: assignInstance. Please specify user params.");
1287         }
1288     }
1289
1290     protected GeneralBuildingBlock getGBBMacroNoUserParamsCreate(ExecuteBuildingBlock executeBB,
1291             Map<ResourceKey, String> lookupKeyMap, String bbName, String key, GeneralBuildingBlock gBB, Service service)
1292             throws Exception {
1293         ServiceInstance serviceInstance = gBB.getServiceInstance();
1294         BBInputSetupParameter parameter = new BBInputSetupParameter.Builder().setExecuteBB(executeBB)
1295                 .setRequestId(executeBB.getRequestId()).setServiceInstance(serviceInstance).setService(service)
1296                 .setBbName(bbName).setLookupKeyMap(lookupKeyMap).setKey(key).build();
1297         if (bbName.contains(NETWORK) && !bbName.contains(NETWORK_COLLECTION)) {
1298             String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
1299             parameter.setResourceId(networkId);
1300             parameter.setModelInfo(new ModelInfo());
1301
1302             if ((!Boolean.TRUE.equals(executeBB.getBuildingBlock().isVirtualLink()))) {
1303                 NetworkResourceCustomization networkCust = getNetworkCustomizationByKey(key, service);
1304                 if (networkCust != null) {
1305                     parameter.getModelInfo().setModelCustomizationUuid(networkCust.getModelCustomizationUUID());
1306                     this.populateL3Network(parameter);
1307                 } else {
1308                     logger.debug("Could not find a network customization with key: {}", key);
1309                 }
1310             } else {
1311                 logger.debug("Orchestrating on Collection Network Resource Customization");
1312                 CollectionNetworkResourceCustomization collectionNetworkResourceCust =
1313                         bbInputSetupUtils.getCatalogCollectionNetworkResourceCustByID(key);
1314                 L3Network l3Network = getVirtualLinkL3Network(lookupKeyMap, bbName, key, networkId,
1315                         collectionNetworkResourceCust, serviceInstance);
1316                 NetworkResourceCustomization networkResourceCustomization = mapperLayer
1317                         .mapCollectionNetworkResourceCustToNetworkResourceCust(collectionNetworkResourceCust);
1318                 if (l3Network != null) {
1319                     l3Network.setModelInfoNetwork(mapperLayer.mapCatalogNetworkToNetwork(networkResourceCustomization));
1320                 }
1321             }
1322         } else if (bbName.contains("Configuration")) {
1323             parameter.setResourceId(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID));
1324             parameter.setModelInfo(new ModelInfo());
1325             parameter.getModelInfo().setModelCustomizationUuid(key);
1326             parameter.setConfigurationResourceKeys(executeBB.getConfigurationResourceKeys());
1327             parameter.setRequestDetails(executeBB.getRequestDetails());
1328             this.populateConfiguration(parameter);
1329         }
1330         if (executeBB.getWorkflowResourceIds() != null) {
1331             parameter.setResourceId(executeBB.getWorkflowResourceIds().getNetworkCollectionId());
1332             this.populateNetworkCollectionAndInstanceGroupAssign(parameter);
1333         }
1334         RelatedInstance relatedVpnBinding =
1335                 bbInputSetupUtils.getRelatedInstanceByType(executeBB.getRequestDetails(), ModelType.vpnBinding);
1336         RelatedInstance relatedLocalNetwork =
1337                 bbInputSetupUtils.getRelatedInstanceByType(executeBB.getRequestDetails(), ModelType.network);
1338         if (relatedVpnBinding != null && relatedLocalNetwork != null) {
1339             org.onap.aai.domain.yang.VpnBinding aaiVpnBinding =
1340                     bbInputSetupUtils.getAAIVpnBinding(relatedVpnBinding.getInstanceId());
1341             org.onap.aai.domain.yang.L3Network aaiLocalNetwork =
1342                     bbInputSetupUtils.getAAIL3Network(relatedLocalNetwork.getInstanceId());
1343             VpnBinding vpnBinding = mapperLayer.mapAAIVpnBinding(aaiVpnBinding);
1344             L3Network localNetwork = mapperLayer.mapAAIL3Network(aaiLocalNetwork);
1345             Optional<org.onap.aai.domain.yang.VpnBinding> aaiAICVpnBindingOp =
1346                     bbInputSetupUtils.getAICVpnBindingFromNetwork(aaiLocalNetwork);
1347             if (aaiAICVpnBindingOp.isPresent()) {
1348                 localNetwork.getVpnBindings().add(mapperLayer.mapAAIVpnBinding(aaiAICVpnBindingOp.get()));
1349             }
1350             ServiceProxy serviceProxy = getServiceProxy(service);
1351             gBB.getServiceInstance().getServiceProxies().add(serviceProxy);
1352             gBB.getCustomer().getVpnBindings().add(vpnBinding);
1353             lookupKeyMap.put(ResourceKey.VPN_ID, vpnBinding.getVpnId());
1354             gBB.getServiceInstance().getNetworks().add(localNetwork);
1355             lookupKeyMap.put(ResourceKey.NETWORK_ID, localNetwork.getNetworkId());
1356         }
1357         return gBB;
1358     }
1359
1360     protected ServiceProxy getServiceProxy(Service service) {
1361         if (!service.getServiceProxyCustomizations().isEmpty()) {
1362             ServiceProxyResourceCustomization serviceProxyCatalog = getServiceProxyResourceCustomization(service);
1363             ServiceProxy serviceProxy = new ServiceProxy();
1364             serviceProxy.setModelInfoServiceProxy(
1365                     mapperLayer.mapServiceProxyCustomizationToServiceProxy(serviceProxyCatalog));
1366             Service sourceService = serviceProxyCatalog.getSourceService();
1367             ServiceInstance sourceServiceShell = new ServiceInstance();
1368             sourceServiceShell
1369                     .setModelInfoServiceInstance(mapperLayer.mapCatalogServiceIntoServiceInstance(sourceService));
1370             serviceProxy.setServiceInstance(sourceServiceShell);
1371             serviceProxy.setType(sourceService.getServiceType());
1372             return serviceProxy;
1373         } else {
1374             return null;
1375         }
1376     }
1377
1378     protected ServiceProxyResourceCustomization getServiceProxyResourceCustomization(Service service) {
1379         ServiceProxyResourceCustomization serviceProxyCatalog = null;
1380         for (ServiceProxyResourceCustomization serviceProxyTemp : service.getServiceProxyCustomizations()) {
1381             if (serviceProxyTemp.getSourceService() != null
1382                     && serviceProxyTemp.getSourceService().getServiceType().equalsIgnoreCase("TRANSPORT")) {
1383                 serviceProxyCatalog = serviceProxyTemp;
1384             }
1385         }
1386         return serviceProxyCatalog;
1387     }
1388
1389     protected L3Network getVirtualLinkL3Network(Map<ResourceKey, String> lookupKeyMap, String bbName, String key,
1390             String networkId, CollectionNetworkResourceCustomization collectionNetworkResourceCust,
1391             ServiceInstance serviceInstance) {
1392         if (collectionNetworkResourceCust != null) {
1393             if ((bbName.equalsIgnoreCase(AssignFlows.NETWORK_A_LA_CARTE.toString())
1394                     || bbName.equalsIgnoreCase(AssignFlows.NETWORK_MACRO.toString()))) {
1395                 L3Network network = createNetwork(lookupKeyMap, null, networkId, null, null);
1396                 serviceInstance.getNetworks().add(network);
1397                 return network;
1398             } else {
1399                 for (L3Network network : serviceInstance.getNetworks()) {
1400                     if (network.getNetworkId().equalsIgnoreCase(networkId)) {
1401                         return network;
1402                     }
1403                 }
1404             }
1405         }
1406         return null;
1407     }
1408
1409     protected NetworkResourceCustomization getNetworkCustomizationByKey(String key, Service service) {
1410         for (NetworkResourceCustomization networkCust : service.getNetworkCustomizations()) {
1411             if (networkCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
1412                 return networkCust;
1413             }
1414         }
1415         return null;
1416     }
1417
1418     protected GeneralBuildingBlock getGBBMacroExistingService(ExecuteBuildingBlock executeBB,
1419             Map<ResourceKey, String> lookupKeyMap, String bbName, String requestAction,
1420             CloudConfiguration cloudConfiguration) throws Exception {
1421         org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null;
1422         String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID);
1423         RequestDetails requestDetails = executeBB.getRequestDetails();
1424         BBInputSetupParameter parameter =
1425                 new BBInputSetupParameter.Builder().setExecuteBB(executeBB).setLookupKeyMap(lookupKeyMap)
1426                         .setBbName(bbName).setRequestAction(requestAction).setCloudConfiguration(cloudConfiguration)
1427                         .setRequestDetails(requestDetails).setResourceId(serviceInstanceId).build();
1428         GeneralBuildingBlock gBB = null;
1429         Service service = null;
1430         if (serviceInstanceId != null) {
1431             aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
1432             if (aaiServiceInstance != null) {
1433                 String modelVersionId = aaiServiceInstance.getModelVersionId();
1434                 if ("upgradeInstance".equalsIgnoreCase(requestAction)) {
1435                     modelVersionId = requestDetails.getModelInfo().getModelVersionId();
1436                 }
1437
1438                 service = bbInputSetupUtils.getCatalogServiceByModelUUID(modelVersionId);
1439
1440                 if (service == null) {
1441                     String message = String.format(
1442                             "Related service instance model not found in MSO CatalogDB: model-version-id=%s",
1443                             aaiServiceInstance.getModelVersionId());
1444                     throw new ServiceModelNotFoundException(message);
1445                 }
1446             } else {
1447                 String message = String.format("Related service instance from AAI not found: service-instance-id=%s",
1448                         serviceInstanceId);
1449                 throw new NoServiceInstanceFoundException(message);
1450             }
1451         }
1452         ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance);
1453         serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service));
1454         parameter.setServiceInstance(serviceInstance);
1455         gBB = populateGBBWithSIAndAdditionalInfo(parameter);
1456
1457         serviceInstance = gBB.getServiceInstance();
1458         CloudRegion cloudRegion = null;
1459         if (cloudConfiguration == null) {
1460             Optional<CloudRegion> cloudRegionOp = cloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance);
1461             if (cloudRegionOp.isPresent()) {
1462                 cloudRegion = cloudRegionOp.get();
1463             }
1464         }
1465         if (cloudConfiguration != null) {
1466             org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
1467             cloudRegion = mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
1468         }
1469         gBB.setCloudRegion(cloudRegion);
1470         if (bbName.contains(VNF) || (bbName.contains(CONTROLLER)
1471                 && (VNF).equalsIgnoreCase(executeBB.getBuildingBlock().getBpmnScope()))) {
1472             for (GenericVnf genericVnf : serviceInstance.getVnfs()) {
1473                 if (lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID) != null
1474                         && genericVnf.getVnfId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID))) {
1475                     org.onap.aai.domain.yang.GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(genericVnf.getVnfId());
1476                     ModelInfo modelInfo = new ModelInfo();
1477                     if (vnf != null) {
1478                         modelInfo.setModelCustomizationUuid(vnf.getModelCustomizationId());
1479                     }
1480                     this.mapCatalogVnf(genericVnf, modelInfo, service);
1481                 }
1482             }
1483         } else if (bbName.contains(VF_MODULE) || (bbName.contains(CONTROLLER)
1484                 && (VF_MODULE).equalsIgnoreCase(executeBB.getBuildingBlock().getBpmnScope()))) {
1485             for (GenericVnf vnf : serviceInstance.getVnfs()) {
1486                 for (VfModule vfModule : vnf.getVfModules()) {
1487                     if (lookupKeyMap.get(ResourceKey.VF_MODULE_ID) != null
1488                             && vfModule.getVfModuleId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VF_MODULE_ID))) {
1489                         String vnfModelCustomizationUUID =
1490                                 this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
1491                         ModelInfo vnfModelInfo = new ModelInfo();
1492                         vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
1493                         this.mapCatalogVnf(vnf, vnfModelInfo, service);
1494                         lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
1495                         String vfModuleCustomizationUUID = this.bbInputSetupUtils
1496                                 .getAAIVfModule(vnf.getVnfId(), vfModule.getVfModuleId()).getModelCustomizationId();
1497                         ModelInfo vfModuleModelInfo = new ModelInfo();
1498                         vfModuleModelInfo.setModelCustomizationId(vfModuleCustomizationUUID);
1499                         this.mapCatalogVfModule(vfModule, vfModuleModelInfo, service, vnfModelCustomizationUUID);
1500                         if (cloudRegion != null) {
1501                             Optional<String> volumeGroupIdOp = getVolumeGroupIdRelatedToVfModule(vnf, vfModuleModelInfo,
1502                                     cloudRegion.getCloudOwner(), cloudRegion.getLcpCloudRegionId(), lookupKeyMap);
1503                             if (volumeGroupIdOp.isPresent()) {
1504                                 lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupIdOp.get());
1505                             }
1506                         }
1507                         if (vfModule.getModelInfoVfModule() != null
1508                                 && vfModule.getModelInfoVfModule().getModelName() != null
1509                                 && vfModule.getModelInfoVfModule().getModelName().contains("helm")) {
1510                             gBB.getRequestContext().setIsHelm(true);
1511                         }
1512                         break;
1513                     }
1514                 }
1515             }
1516         } else if (bbName.contains(VOLUME_GROUP)) {
1517             for (GenericVnf vnf : serviceInstance.getVnfs()) {
1518                 for (VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
1519                     if (lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID) != null && volumeGroup.getVolumeGroupId()
1520                             .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID))) {
1521                         String vnfModelCustomizationUUID =
1522                                 this.bbInputSetupUtils.getAAIGenericVnf(vnf.getVnfId()).getModelCustomizationId();
1523                         ModelInfo vnfModelInfo = new ModelInfo();
1524                         vnfModelInfo.setModelCustomizationUuid(vnfModelCustomizationUUID);
1525                         this.mapCatalogVnf(vnf, vnfModelInfo, service);
1526                         lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnf.getVnfId());
1527                         if (cloudRegion != null) {
1528                             String volumeGroupCustomizationUUID =
1529                                     this.bbInputSetupUtils
1530                                             .getAAIVolumeGroup(cloudRegion.getCloudOwner(),
1531                                                     cloudRegion.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId())
1532                                             .getModelCustomizationId();
1533                             ModelInfo volumeGroupModelInfo = new ModelInfo();
1534                             volumeGroupModelInfo.setModelCustomizationId(volumeGroupCustomizationUUID);
1535                             this.mapCatalogVolumeGroup(volumeGroup, volumeGroupModelInfo, service,
1536                                     vnfModelCustomizationUUID);
1537                         }
1538                         break;
1539                     }
1540                 }
1541             }
1542         } else if (bbName.contains(NETWORK)) {
1543             for (L3Network network : serviceInstance.getNetworks()) {
1544                 if (lookupKeyMap.get(ResourceKey.NETWORK_ID) != null
1545                         && network.getNetworkId().equalsIgnoreCase(lookupKeyMap.get(ResourceKey.NETWORK_ID))) {
1546                     String networkCustomizationUUID =
1547                             this.bbInputSetupUtils.getAAIL3Network(network.getNetworkId()).getModelCustomizationId();
1548                     ModelInfo modelInfo = new ModelInfo();
1549                     modelInfo.setModelCustomizationUuid(networkCustomizationUUID);
1550                     this.mapCatalogNetwork(network, modelInfo, service);
1551                     break;
1552                 }
1553             }
1554         } else if (bbName.contains("Fabric")) {
1555             for (Configuration configuration : serviceInstance.getConfigurations()) {
1556                 if (lookupKeyMap.get(ResourceKey.CONFIGURATION_ID) != null && configuration.getConfigurationId()
1557                         .equalsIgnoreCase(lookupKeyMap.get(ResourceKey.CONFIGURATION_ID))) {
1558                     String configurationCustUUID = this.bbInputSetupUtils
1559                             .getAAIConfiguration(configuration.getConfigurationId()).getModelCustomizationId();
1560                     ModelInfo modelInfo = new ModelInfo();
1561                     modelInfo.setModelCustomizationUuid(configurationCustUUID);
1562                     this.mapCatalogConfiguration(configuration, modelInfo, service,
1563                             executeBB.getConfigurationResourceKeys());
1564                     break;
1565                 }
1566             }
1567         }
1568         if (executeBB.getWorkflowResourceIds() != null) {
1569             parameter.setResourceId(executeBB.getWorkflowResourceIds().getNetworkCollectionId());
1570             parameter.setKey(executeBB.getBuildingBlock().getKey());
1571             this.populateNetworkCollectionAndInstanceGroupAssign(parameter);
1572         }
1573         return gBB;
1574     }
1575
1576     protected GeneralBuildingBlock getGBBMacroUserParams(ExecuteBuildingBlock executeBB, RequestDetails requestDetails,
1577             Map<ResourceKey, String> lookupKeyMap, String vnfType, String bbName, String key, GeneralBuildingBlock gBB,
1578             RequestParameters requestParams, Service service, String input) throws Exception {
1579         ServiceInstance serviceInstance = gBB.getServiceInstance();
1580         org.onap.so.serviceinstancebeans.Service serviceMacro =
1581                 mapper.readValue(input, org.onap.so.serviceinstancebeans.Service.class);
1582
1583         Resources resources = serviceMacro.getResources();
1584         Vnfs vnfs = null;
1585         VfModules vfModules = null;
1586         Networks networks = null;
1587
1588         CloudConfiguration cloudConfiguration = requestDetails.getCloudConfiguration();
1589         CloudRegion cloudRegion = setCloudConfiguration(gBB, cloudConfiguration);
1590
1591         BBInputSetupParameter parameter =
1592                 new BBInputSetupParameter.Builder().setRequestId(executeBB.getRequestId()).setService(service)
1593                         .setBbName(bbName).setServiceInstance(serviceInstance).setLookupKeyMap(lookupKeyMap).build();
1594         if (bbName.contains(VNF) || (bbName.contains(CONTROLLER)
1595                 && (VNF).equalsIgnoreCase(executeBB.getBuildingBlock().getBpmnScope()))) {
1596             String vnfInstanceName = lookupKeyMap.get(ResourceKey.VNF_INSTANCE_NAME);
1597             if (StringUtils.isNotBlank(vnfInstanceName)) {
1598                 vnfs = findVnfsByInstanceName(vnfInstanceName, resources);
1599             } else {
1600                 vnfs = findVnfsByKey(key, resources);
1601             }
1602
1603             // Vnf level cloud configuration takes precedence over service level cloud configuration.
1604             if (vnfs.getCloudConfiguration() != null) {
1605                 setCloudConfiguration(gBB, vnfs.getCloudConfiguration());
1606             }
1607
1608             String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
1609             // This stores the vnf id in request db to be retrieved later when
1610             // working on a vf module or volume group
1611             InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
1612             if (request != null) {
1613                 this.bbInputSetupUtils.updateInfraActiveRequestVnfId(request, vnfId);
1614             }
1615             parameter.setModelInfo(vnfs.getModelInfo());
1616             parameter.setInstanceName(vnfs.getInstanceName());
1617             parameter.setPlatform(vnfs.getPlatform());
1618             parameter.setLineOfBusiness(vnfs.getLineOfBusiness());
1619             parameter.setResourceId(vnfId);
1620             parameter.setVnfType(vnfType);
1621             parameter.setInstanceParams(vnfs.getInstanceParams());
1622             parameter.setProductFamilyId(requestDetails.getRequestInfo().getProductFamilyId());
1623             String applicationId = "";
1624             if (vnfs.getApplicationId() != null) {
1625                 applicationId = vnfs.getApplicationId();
1626             }
1627             parameter.setApplicationId(applicationId);
1628             this.populateGenericVnf(parameter);
1629         } else if (bbName.contains(PNF) || (bbName.contains(CONTROLLER)
1630                 && (PNF).equalsIgnoreCase(executeBB.getBuildingBlock().getBpmnScope()))) {
1631             String pnfId = lookupKeyMap.get(ResourceKey.PNF);
1632             resources.getPnfs().stream()
1633                     .filter(pnfs -> Objects.equals(key, pnfs.getModelInfo().getModelCustomizationId())).findFirst()
1634                     .ifPresent(pnfs -> BBInputSetupPnf.populatePnfToServiceInstance(pnfs, pnfId, serviceInstance));
1635         } else if (bbName.contains(VF_MODULE) || bbName.contains(VOLUME_GROUP) || (bbName.contains(CONTROLLER)
1636                 && (VF_MODULE).equalsIgnoreCase(executeBB.getBuildingBlock().getBpmnScope()))) {
1637             String vfModuleInstanceName = lookupKeyMap.get(ResourceKey.VF_MODULE_INSTANCE_NAME);
1638             if (StringUtils.isNotBlank(vfModuleInstanceName)) {
1639                 vfModules = getVfModulesByInstanceName(vfModuleInstanceName, resources);
1640             } else {
1641                 vfModules = getVfModulesByKey(key, resources);
1642             }
1643
1644             String vfModulesName = vfModules.getInstanceName();
1645             String vfModulesModelCustId = vfModules.getModelInfo().getModelCustomizationId();
1646             // Get the Vnf associated with vfModule
1647             Optional<org.onap.so.serviceinstancebeans.Vnfs> parentVnf = resources.getVnfs().stream()
1648                     .filter(aVnf -> aVnf.getCloudConfiguration() != null)
1649                     .filter(aVnf -> aVnf.getVfModules().stream()
1650                             .anyMatch(aVfModules -> aVfModules.getInstanceName().equals(vfModulesName) && aVfModules
1651                                     .getModelInfo().getModelCustomizationId().equals(vfModulesModelCustId)))
1652                     .findAny();
1653
1654             // Get the cloud configuration from this Vnf
1655             if (parentVnf.isPresent()) {
1656                 cloudRegion = setCloudConfiguration(gBB, parentVnf.get().getCloudConfiguration());
1657             }
1658
1659             lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, getVnfId(executeBB, lookupKeyMap));
1660
1661             parameter.setModelInfo(vfModules.getModelInfo());
1662             if (bbName.contains(VOLUME_GROUP)) {
1663                 parameter.setResourceId(lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID));
1664                 parameter.setInstanceName(vfModules.getVolumeGroupInstanceName());
1665                 parameter.setVnfType(vnfType);
1666                 parameter.setInstanceParams(vfModules.getInstanceParams());
1667                 ServiceModel serviceModel = new ServiceModel();
1668                 serviceModel.setCurrentService(service);
1669                 parameter.setServiceModel(serviceModel);
1670                 this.populateVolumeGroup(parameter);
1671             } else {
1672                 parameter.setResourceId(lookupKeyMap.get(ResourceKey.VF_MODULE_ID));
1673                 CloudConfiguration cloudConfig = new CloudConfiguration();
1674                 cloudConfig.setLcpCloudRegionId(cloudRegion.getLcpCloudRegionId());
1675                 cloudConfig.setCloudOwner(cloudRegion.getCloudOwner());
1676                 ServiceModel serviceModel = new ServiceModel();
1677                 serviceModel.setCurrentService(service);
1678                 parameter.setServiceModel(serviceModel);
1679                 parameter.setCloudConfiguration(cloudConfig);
1680                 parameter.setInstanceName(vfModules.getInstanceName());
1681                 parameter.setInstanceParams(vfModules.getInstanceParams());
1682                 this.populateVfModule(parameter);
1683                 gBB.getRequestContext().setIsHelm(parameter.getIsHelm());
1684             }
1685         } else if (bbName.contains(NETWORK)) {
1686             networks = findNetworksByKey(key, resources);
1687             String networkId = lookupKeyMap.get(ResourceKey.NETWORK_ID);
1688             if (networks != null) {
1689                 // If service level cloud configuration is not provided then get it from networks.
1690                 if (cloudConfiguration == null) {
1691                     Optional<org.onap.so.serviceinstancebeans.Networks> netWithCloudConfig = resources.getNetworks()
1692                             .stream().filter(aNetwork -> aNetwork.getCloudConfiguration() != null).findAny();
1693                     if (netWithCloudConfig.isPresent()) {
1694                         setCloudConfiguration(gBB, netWithCloudConfig.get().getCloudConfiguration());
1695                     } else {
1696                         logger.debug("Could not find any cloud configuration for this request.");
1697                     }
1698                 }
1699                 parameter.setInstanceName(networks.getInstanceName());
1700                 parameter.setModelInfo(networks.getModelInfo());
1701                 parameter.setInstanceParams(networks.getInstanceParams());
1702                 parameter.setResourceId(networkId);
1703                 this.populateL3Network(parameter);
1704             }
1705         } else if (bbName.contains("Configuration")) {
1706             String configurationId = lookupKeyMap.get(ResourceKey.CONFIGURATION_ID);
1707             ModelInfo configurationModelInfo = new ModelInfo();
1708             configurationModelInfo.setModelCustomizationUuid(key);
1709             ConfigurationResourceCustomization configurationCust =
1710                     findConfigurationResourceCustomization(configurationModelInfo, service);
1711             if (configurationCust != null) {
1712                 parameter.setModelInfo(configurationModelInfo);
1713                 parameter.setResourceId(configurationId);
1714                 parameter.setConfigurationResourceKeys(executeBB.getConfigurationResourceKeys());
1715                 parameter.setRequestDetails(executeBB.getRequestDetails());
1716                 this.populateConfiguration(parameter);
1717             } else {
1718                 logger.debug("Could not find a configuration customization with key: {}", key);
1719             }
1720         }
1721         return gBB;
1722     }
1723
1724     /**
1725      * setCloudConfiguration - set cloud info on a building block.
1726      * 
1727      * @param gBB
1728      * @param cloudConfiguration
1729      * @return CloudRegion
1730      * @throws Exception
1731      */
1732     private CloudRegion setCloudConfiguration(GeneralBuildingBlock gBB, CloudConfiguration cloudConfiguration)
1733             throws Exception {
1734         org.onap.aai.domain.yang.CloudRegion aaiCloudRegion = bbInputSetupUtils.getCloudRegion(cloudConfiguration);
1735         Tenant tenant = getTenant(cloudConfiguration, aaiCloudRegion);
1736         gBB.setTenant(tenant);
1737         CloudRegion cloudRegion = mapperLayer.mapCloudRegion(cloudConfiguration, aaiCloudRegion);
1738         gBB.setCloudRegion(cloudRegion);
1739         return cloudRegion;
1740     }
1741
1742     protected Networks findNetworksByKey(String key, Resources resources) {
1743         for (Networks networks : resources.getNetworks()) {
1744             if (networks.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
1745                 return networks;
1746             }
1747         }
1748         return null;
1749     }
1750
1751     protected VfModules getVfModulesByInstanceName(String vfModuleInstanceName, Resources resources) {
1752         for (Vnfs vnfs : resources.getVnfs()) {
1753             for (VfModules vfModules : vnfs.getVfModules()) {
1754                 if (vfModules.getInstanceName().equals(vfModuleInstanceName)) {
1755                     return vfModules;
1756                 }
1757             }
1758         }
1759         throw new ResourceNotFoundException(
1760                 "Could not find vf-module with instanceName: " + vfModuleInstanceName + " in userparams");
1761     }
1762
1763     protected VfModules getVfModulesByKey(String key, Resources resources) {
1764         for (Vnfs vnfs : resources.getVnfs()) {
1765             for (VfModules vfModules : vnfs.getVfModules()) {
1766                 if (vfModules.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
1767                     return vfModules;
1768                 }
1769             }
1770         }
1771         throw new ResourceNotFoundException("Could not find vf-module with key: " + key + " in userparams");
1772     }
1773
1774     protected Vnfs findVnfsByInstanceName(String instanceName, Resources resources) {
1775         for (Vnfs tempVnfs : resources.getVnfs()) {
1776             if (tempVnfs.getInstanceName().equals(instanceName)) {
1777                 return tempVnfs;
1778             }
1779         }
1780         throw new ResourceNotFoundException("Could not find vnf with instanceName: " + instanceName + " in userparams");
1781     }
1782
1783     protected Vnfs findVnfsByKey(String key, Resources resources) {
1784         for (Vnfs tempVnfs : resources.getVnfs()) {
1785             if (tempVnfs.getModelInfo().getModelCustomizationId().equalsIgnoreCase(key)) {
1786                 return tempVnfs;
1787             }
1788         }
1789         throw new ResourceNotFoundException("Could not find vnf with key: " + key + " in userparams");
1790     }
1791
1792     protected String getVnfId(ExecuteBuildingBlock executeBB, Map<ResourceKey, String> lookupKeyMap) {
1793         String vnfId = lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID);
1794         if (vnfId == null) {
1795             InfraActiveRequests request = this.bbInputSetupUtils.getInfraActiveRequest(executeBB.getRequestId());
1796             vnfId = request.getVnfId();
1797         }
1798
1799         return vnfId;
1800     }
1801
1802     protected String generateRandomUUID() {
1803         return UUID.randomUUID().toString();
1804     }
1805
1806     protected ServiceInstance getServiceInstanceHelper(RequestDetails requestDetails, Customer customer,
1807             Project project, OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId,
1808             boolean aLaCarte, Service service, String bbName) throws Exception {
1809         if (requestDetails.getRequestInfo().getInstanceName() == null && aLaCarte
1810                 && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
1811             throw new Exception("Request invalid missing: RequestInfo:InstanceName");
1812         } else {
1813             org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI;
1814             serviceInstanceAAI = getServiceInstanceAAI(requestDetails, customer, serviceInstanceId, aLaCarte, bbName);
1815             if (serviceInstanceAAI != null) {
1816                 lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
1817                 return this.getExistingServiceInstance(serviceInstanceAAI);
1818             } else {
1819                 return createServiceInstance(requestDetails, project, owningEntity, lookupKeyMap, serviceInstanceId);
1820             }
1821         }
1822     }
1823
1824     private org.onap.aai.domain.yang.ServiceInstance getServiceInstanceAAI(RequestDetails requestDetails,
1825             Customer customer, String serviceInstanceId, boolean aLaCarte, String bbName) throws Exception {
1826         org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI = null;
1827         if (aLaCarte && bbName.equalsIgnoreCase(AssignFlows.SERVICE_INSTANCE.toString())) {
1828             serviceInstanceAAI = bbInputSetupUtils
1829                     .getAAIServiceInstanceByName(requestDetails.getRequestInfo().getInstanceName(), customer);
1830         }
1831         if (serviceInstanceId != null && serviceInstanceAAI == null) {
1832             if (customer != null && customer.getServiceSubscription() != null) {
1833                 serviceInstanceAAI =
1834                         bbInputSetupUtils.getAAIServiceInstanceByIdAndCustomer(customer.getGlobalCustomerId(),
1835                                 customer.getServiceSubscription().getServiceType(), serviceInstanceId);
1836             } else {
1837                 serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId);
1838             }
1839         }
1840         return serviceInstanceAAI;
1841     }
1842
1843     protected ServiceInstance createServiceInstance(RequestDetails requestDetails, Project project,
1844             OwningEntity owningEntity, Map<ResourceKey, String> lookupKeyMap, String serviceInstanceId) {
1845         ServiceInstance serviceInstance = new ServiceInstance();
1846         lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId);
1847         serviceInstance.setServiceInstanceId(serviceInstanceId);
1848         if (requestDetails.getRequestInfo() != null) {
1849             serviceInstance.setServiceInstanceName(requestDetails.getRequestInfo().getInstanceName());
1850         }
1851         serviceInstance.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
1852         serviceInstance.setProject(project);
1853         serviceInstance.setOwningEntity(owningEntity);
1854         return serviceInstance;
1855     }
1856
1857     /**
1858      * This method is used for getting the existing service instance.
1859      *
1860      * This will map the serviceInstanceAAI to serviceInstance and return the serviceInstance.
1861      *
1862      * @throws Exception
1863      * @return serviceInstance
1864      */
1865     public ServiceInstance getExistingServiceInstance(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI)
1866             throws Exception {
1867         ServiceInstance serviceInstance = mapperLayer.mapAAIServiceInstanceIntoServiceInstance(serviceInstanceAAI);
1868         if (serviceInstanceAAI.getRelationshipList() != null
1869                 && serviceInstanceAAI.getRelationshipList().getRelationship() != null
1870                 && !serviceInstanceAAI.getRelationshipList().getRelationship().isEmpty()) {
1871             addRelationshipsToSI(serviceInstanceAAI, serviceInstance);
1872         }
1873         return serviceInstance;
1874     }
1875
1876     protected void populateNetworkCollectionAndInstanceGroupAssign(BBInputSetupParameter parameter) throws Exception {
1877         if (parameter.getServiceInstance().getCollection() == null
1878                 && parameter.getBbName().equalsIgnoreCase(AssignFlows.NETWORK_COLLECTION.toString())) {
1879             Collection collection = this.createCollection(parameter.getResourceId());
1880             parameter.getServiceInstance().setCollection(collection);
1881             this.mapCatalogCollection(parameter.getService(), parameter.getServiceInstance().getCollection(),
1882                     parameter.getKey());
1883             if (isVlanTagging(parameter.getService(), parameter.getKey())) {
1884                 InstanceGroup instanceGroup = this.createInstanceGroup();
1885                 parameter.getServiceInstance().getCollection().setInstanceGroup(instanceGroup);
1886                 this.mapCatalogNetworkCollectionInstanceGroup(parameter.getService(),
1887                         parameter.getServiceInstance().getCollection().getInstanceGroup(), parameter.getKey());
1888             }
1889         }
1890     }
1891
1892     protected CollectionResourceCustomization findCatalogNetworkCollection(Service service, String key) {
1893         for (CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()) {
1894             if (collectionCust.getModelCustomizationUUID().equalsIgnoreCase(key)) {
1895                 return collectionCust;
1896             }
1897         }
1898         return null;
1899     }
1900
1901     protected boolean isVlanTagging(Service service, String key) {
1902         CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
1903         if (collectionCust != null) {
1904             CollectionResource collectionResource = collectionCust.getCollectionResource();
1905             if (collectionResource != null && collectionResource.getInstanceGroup() != null
1906                     && collectionResource.getInstanceGroup().getToscaNodeType() != null
1907                     && collectionResource.getInstanceGroup().getToscaNodeType().contains("NetworkCollection")) {
1908                 return true;
1909             }
1910         }
1911         return false;
1912     }
1913
1914     protected void mapCatalogNetworkCollectionInstanceGroup(Service service, InstanceGroup instanceGroup, String key) {
1915         CollectionResourceCustomization collectionCust = this.findCatalogNetworkCollection(service, key);
1916         org.onap.so.db.catalog.beans.InstanceGroup catalogInstanceGroup = null;
1917         if (collectionCust != null) {
1918             catalogInstanceGroup = collectionCust.getCollectionResource().getInstanceGroup();
1919         }
1920         instanceGroup.setModelInfoInstanceGroup(
1921                 mapperLayer.mapCatalogInstanceGroupToInstanceGroup(collectionCust, catalogInstanceGroup));
1922     }
1923
1924     protected void mapCatalogCollection(Service service, Collection collection, String key) {
1925         CollectionResourceCustomization collectionCust = findCatalogNetworkCollection(service, key);
1926         if (collectionCust != null) {
1927             CollectionResource collectionResource = collectionCust.getCollectionResource();
1928             if (collectionResource != null) {
1929                 collection.setModelInfoCollection(
1930                         mapperLayer.mapCatalogCollectionToCollection(collectionCust, collectionResource));
1931             }
1932         }
1933     }
1934
1935     protected Collection createCollection(String collectionId) {
1936         Collection collection = new Collection();
1937         collection.setId(collectionId);
1938         collection.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
1939         return collection;
1940     }
1941
1942     protected InstanceGroup createInstanceGroup() {
1943         InstanceGroup instanceGroup = new InstanceGroup();
1944         String instanceGroupId = this.generateRandomUUID();
1945         instanceGroup.setId(instanceGroupId);
1946         return instanceGroup;
1947     }
1948
1949     protected void addRelationshipsToSI(org.onap.aai.domain.yang.ServiceInstance serviceInstanceAAI,
1950             ServiceInstance serviceInstance) throws Exception {
1951         AAIResultWrapper serviceInstanceWrapper = new AAIResultWrapper(
1952                 new AAICommonObjectMapperProvider().getMapper().writeValueAsString(serviceInstanceAAI));
1953         Optional<Relationships> relationshipsOp = serviceInstanceWrapper.getRelationships();
1954         if (relationshipsOp.isPresent()) {
1955             mapRelationship(serviceInstance, relationshipsOp.get());
1956         }
1957     }
1958
1959     private void mapRelationship(ServiceInstance serviceInstance, Relationships relationships) {
1960         this.mapProject(relationships.getByType(Types.PROJECT, uri -> uri.nodesOnly(true)), serviceInstance);
1961         this.mapOwningEntity(relationships.getByType(Types.OWNING_ENTITY, uri -> uri.nodesOnly(true)), serviceInstance);
1962         this.mapL3Networks(relationships.getRelatedUris(Types.L3_NETWORK), serviceInstance.getNetworks());
1963         this.mapGenericVnfs(relationships.getRelatedUris(Types.GENERIC_VNF), serviceInstance.getVnfs());
1964         this.mapPnfs(relationships.getRelatedUris(Types.PNF), serviceInstance.getPnfs());
1965         this.mapCollection(relationships.getByType(Types.COLLECTION), serviceInstance);
1966         this.mapConfigurations(relationships.getRelatedUris(Types.CONFIGURATION), serviceInstance.getConfigurations());
1967     }
1968
1969     protected void mapConfigurations(List<AAIResourceUri> relatedAAIUris, List<Configuration> configurations) {
1970         for (AAIResourceUri aaiResourceUri : relatedAAIUris) {
1971             configurations.add(mapConfiguration(aaiResourceUri));
1972         }
1973     }
1974
1975     protected Configuration mapConfiguration(AAIResourceUri aaiResourceUri) {
1976         AAIResultWrapper aaiConfigurationWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
1977         Optional<org.onap.aai.domain.yang.Configuration> aaiConfigurationOp =
1978                 aaiConfigurationWrapper.asBean(org.onap.aai.domain.yang.Configuration.class);
1979         if (!aaiConfigurationOp.isPresent()) {
1980             return null;
1981         }
1982
1983         return this.mapperLayer.mapAAIConfiguration(aaiConfigurationOp.get());
1984     }
1985
1986     protected void mapGenericVnfs(List<AAIResourceUri> list, List<GenericVnf> genericVnfs) {
1987         for (AAIResourceUri aaiResourceUri : list) {
1988             genericVnfs.add(this.mapGenericVnf(aaiResourceUri));
1989         }
1990     }
1991
1992     protected GenericVnf mapGenericVnf(AAIResourceUri aaiResourceUri) {
1993         AAIResultWrapper aaiGenericVnfWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
1994         Optional<org.onap.aai.domain.yang.GenericVnf> aaiGenericVnfOp =
1995                 aaiGenericVnfWrapper.asBean(org.onap.aai.domain.yang.GenericVnf.class);
1996         if (!aaiGenericVnfOp.isPresent()) {
1997             return null;
1998         }
1999
2000         GenericVnf genericVnf = this.mapperLayer.mapAAIGenericVnfIntoGenericVnf(aaiGenericVnfOp.get());
2001
2002         Optional<Relationships> relationshipsOp = aaiGenericVnfWrapper.getRelationships();
2003         if (relationshipsOp.isPresent()) {
2004             Relationships relationships = relationshipsOp.get();
2005             this.mapPlatform(relationships.getByType(Types.PLATFORM, uri -> uri.nodesOnly(true)), genericVnf);
2006             this.mapLineOfBusiness(relationships.getByType(Types.LINE_OF_BUSINESS, uri -> uri.nodesOnly(true)),
2007                     genericVnf);
2008             genericVnf.getVolumeGroups().addAll(mapVolumeGroups(relationships.getByType(Types.VOLUME_GROUP)));
2009             genericVnf.getInstanceGroups().addAll(mapInstanceGroups(relationships.getByType(Types.INSTANCE_GROUP)));
2010         }
2011
2012         return genericVnf;
2013     }
2014
2015     protected void mapPnfs(List<AAIResourceUri> list, List<Pnf> pnfs) {
2016         for (AAIResourceUri aaiResourceUri : list) {
2017             pnfs.add(this.mapPnf(aaiResourceUri));
2018         }
2019     }
2020
2021     protected Pnf mapPnf(AAIResourceUri aaiResourceUri) {
2022         AAIResultWrapper aaiPnfWrapper = this.bbInputSetupUtils.getAAIResourceDepthOne(aaiResourceUri);
2023         Optional<org.onap.aai.domain.yang.Pnf> aaiPnfWrapperOp =
2024                 aaiPnfWrapper.asBean(org.onap.aai.domain.yang.Pnf.class);
2025         return aaiPnfWrapperOp.map(pnf -> this.mapperLayer.mapAAIPnfIntoPnf(pnf)).orElse(null);
2026     }
2027
2028     protected List<InstanceGroup> mapInstanceGroups(List<AAIResultWrapper> instanceGroups) {
2029         List<InstanceGroup> instanceGroupsList = new ArrayList<>();
2030         for (AAIResultWrapper volumeGroupWrapper : instanceGroups) {
2031             instanceGroupsList.add(this.mapInstanceGroup(volumeGroupWrapper));
2032         }
2033         return instanceGroupsList;
2034     }
2035
2036     protected InstanceGroup mapInstanceGroup(AAIResultWrapper instanceGroupWrapper) {
2037         Optional<org.onap.aai.domain.yang.InstanceGroup> aaiInstanceGroupOp =
2038                 instanceGroupWrapper.asBean(org.onap.aai.domain.yang.InstanceGroup.class);
2039         org.onap.aai.domain.yang.InstanceGroup aaiInstanceGroup = null;
2040
2041         if (!aaiInstanceGroupOp.isPresent()) {
2042             return null;
2043         }
2044
2045         aaiInstanceGroup = aaiInstanceGroupOp.get();
2046         InstanceGroup instanceGroup = this.mapperLayer.mapAAIInstanceGroupIntoInstanceGroup(aaiInstanceGroup);
2047         instanceGroup.setModelInfoInstanceGroup(this.mapperLayer.mapCatalogInstanceGroupToInstanceGroup(null,
2048                 this.bbInputSetupUtils.getCatalogInstanceGroup(aaiInstanceGroup.getModelVersionId())));
2049         return instanceGroup;
2050     }
2051
2052     protected List<VolumeGroup> mapVolumeGroups(List<AAIResultWrapper> volumeGroups) {
2053         List<VolumeGroup> volumeGroupsList = new ArrayList<>();
2054         for (AAIResultWrapper volumeGroupWrapper : volumeGroups) {
2055             volumeGroupsList.add(this.mapVolumeGroup(volumeGroupWrapper));
2056         }
2057         return volumeGroupsList;
2058     }
2059
2060     protected VolumeGroup mapVolumeGroup(AAIResultWrapper volumeGroupWrapper) {
2061         Optional<org.onap.aai.domain.yang.VolumeGroup> aaiVolumeGroupOp =
2062                 volumeGroupWrapper.asBean(org.onap.aai.domain.yang.VolumeGroup.class);
2063         org.onap.aai.domain.yang.VolumeGroup aaiVolumeGroup = null;
2064
2065         if (!aaiVolumeGroupOp.isPresent()) {
2066             return null;
2067         }
2068
2069         aaiVolumeGroup = aaiVolumeGroupOp.get();
2070         return this.mapperLayer.mapAAIVolumeGroup(aaiVolumeGroup);
2071     }
2072
2073     protected void mapLineOfBusiness(List<AAIResultWrapper> lineOfBusinesses, GenericVnf genericVnf) {
2074         if (!lineOfBusinesses.isEmpty()) {
2075             AAIResultWrapper lineOfBusinessWrapper = lineOfBusinesses.get(0);
2076             Optional<org.onap.aai.domain.yang.LineOfBusiness> aaiLineOfBusinessOp =
2077                     lineOfBusinessWrapper.asBean(org.onap.aai.domain.yang.LineOfBusiness.class);
2078             if (aaiLineOfBusinessOp.isPresent()) {
2079                 LineOfBusiness lineOfBusiness = this.mapperLayer.mapAAILineOfBusiness(aaiLineOfBusinessOp.get());
2080                 genericVnf.setLineOfBusiness(lineOfBusiness);
2081             }
2082         }
2083     }
2084
2085     protected void mapPlatform(List<AAIResultWrapper> platforms, GenericVnf genericVnf) {
2086         if (!platforms.isEmpty()) {
2087             AAIResultWrapper platformWrapper = platforms.get(0);
2088             Optional<org.onap.aai.domain.yang.Platform> aaiPlatformOp =
2089                     platformWrapper.asBean(org.onap.aai.domain.yang.Platform.class);
2090             if (aaiPlatformOp.isPresent()) {
2091                 Platform platform = this.mapperLayer.mapAAIPlatform(aaiPlatformOp.get());
2092                 genericVnf.setPlatform(platform);
2093             }
2094         }
2095     }
2096
2097     protected void mapCollection(List<AAIResultWrapper> collections, ServiceInstance serviceInstance) {
2098         if (!collections.isEmpty()) {
2099             AAIResultWrapper collectionWrapper = collections.get(0);
2100             Optional<org.onap.aai.domain.yang.Collection> aaiCollectionOp =
2101                     collectionWrapper.asBean(org.onap.aai.domain.yang.Collection.class);
2102             aaiCollectionOp.ifPresent(
2103                     collection -> serviceInstanceSetCollection(serviceInstance, collectionWrapper, collection));
2104         }
2105     }
2106
2107     private void serviceInstanceSetCollection(ServiceInstance serviceInstance, AAIResultWrapper collectionWrapper,
2108             org.onap.aai.domain.yang.Collection aaiCollection) {
2109         Collection collection = getCollection(aaiCollection);
2110         Optional<Relationships> relationshipsOp = collectionWrapper.getRelationships();
2111         relationshipsOp.ifPresent(relationships -> setInstanceGroupForCollection(collection, relationships));
2112         serviceInstance.setCollection(collection);
2113     }
2114
2115     private void setInstanceGroupForCollection(Collection collection, Relationships relationships) {
2116         List<InstanceGroup> instanceGroupsList = mapInstanceGroups(relationships.getByType(Types.INSTANCE_GROUP));
2117         if (!instanceGroupsList.isEmpty()) {
2118             collection.setInstanceGroup(instanceGroupsList.get(0));
2119         }
2120     }
2121
2122     private Collection getCollection(org.onap.aai.domain.yang.Collection aaiCollection) {
2123         Collection collection = this.mapperLayer.mapAAICollectionIntoCollection(aaiCollection);
2124         NetworkCollectionResourceCustomization collectionResourceCust = bbInputSetupUtils
2125                 .getCatalogNetworkCollectionResourceCustByID(aaiCollection.getCollectionCustomizationId());
2126         collection.setModelInfoCollection(mapperLayer.mapCatalogCollectionToCollection(collectionResourceCust,
2127                 collectionResourceCust.getCollectionResource()));
2128         return collection;
2129     }
2130
2131     protected void mapL3Networks(List<AAIResourceUri> list, List<L3Network> l3Networks) {
2132         for (AAIResourceUri aaiResourceUri : list) {
2133             l3Networks.add(this.mapL3Network(aaiResourceUri));
2134         }
2135     }
2136
2137     protected L3Network mapL3Network(AAIResourceUri aaiResourceUri) {
2138         AAIResultWrapper aaiNetworkWrapper = this.bbInputSetupUtils.getAAIResourceDepthTwo(aaiResourceUri);
2139         Optional<org.onap.aai.domain.yang.L3Network> aaiL3NetworkOp =
2140                 aaiNetworkWrapper.asBean(org.onap.aai.domain.yang.L3Network.class);
2141         org.onap.aai.domain.yang.L3Network aaiL3Network = null;
2142
2143         if (!aaiL3NetworkOp.isPresent()) {
2144             return null;
2145         }
2146
2147         aaiL3Network = aaiL3NetworkOp.get();
2148         L3Network network = this.mapperLayer.mapAAIL3Network(aaiL3Network);
2149
2150         Optional<Relationships> relationshipsOp = aaiNetworkWrapper.getRelationships();
2151         if (relationshipsOp.isPresent()) {
2152             Relationships relationships = relationshipsOp.get();
2153             this.mapNetworkPolicies(relationships.getByType(Types.NETWORK_POLICY), network.getNetworkPolicies());
2154             mapRouteTableReferences(relationships.getByType(Types.ROUTE_TABLE_REFERENCE),
2155                     network.getContrailNetworkRouteTableReferences());
2156         }
2157
2158         return network;
2159     }
2160
2161     protected void mapNetworkPolicies(List<AAIResultWrapper> aaiNetworkPolicies, List<NetworkPolicy> networkPolicies) {
2162         for (AAIResultWrapper networkPolicyWrapper : aaiNetworkPolicies) {
2163             networkPolicies.add(this.mapNetworkPolicy(networkPolicyWrapper));
2164         }
2165     }
2166
2167     protected NetworkPolicy mapNetworkPolicy(AAIResultWrapper networkPolicyWrapper) {
2168         Optional<org.onap.aai.domain.yang.NetworkPolicy> aaiNetworkPolicyOp =
2169                 networkPolicyWrapper.asBean(org.onap.aai.domain.yang.NetworkPolicy.class);
2170         org.onap.aai.domain.yang.NetworkPolicy aaiNetworkPolicy = null;
2171
2172         if (!aaiNetworkPolicyOp.isPresent()) {
2173             return null;
2174         }
2175
2176         aaiNetworkPolicy = aaiNetworkPolicyOp.get();
2177         return this.mapperLayer.mapAAINetworkPolicy(aaiNetworkPolicy);
2178     }
2179
2180     protected void mapRouteTableReferences(List<AAIResultWrapper> routeTableReferences,
2181             List<RouteTableReference> contrailNetworkRouteTableReferences) {
2182         for (AAIResultWrapper routeTableReferenceWrapper : routeTableReferences) {
2183             contrailNetworkRouteTableReferences.add(this.mapRouteTableReference(routeTableReferenceWrapper));
2184         }
2185     }
2186
2187     protected RouteTableReference mapRouteTableReference(AAIResultWrapper routeTableReferenceWrapper) {
2188         Optional<org.onap.aai.domain.yang.RouteTableReference> aaiRouteTableReferenceOp =
2189                 routeTableReferenceWrapper.asBean(org.onap.aai.domain.yang.RouteTableReference.class);
2190         org.onap.aai.domain.yang.RouteTableReference aaiRouteTableReference = null;
2191
2192         if (!aaiRouteTableReferenceOp.isPresent()) {
2193             return null;
2194         }
2195
2196         aaiRouteTableReference = aaiRouteTableReferenceOp.get();
2197         return this.mapperLayer.mapAAIRouteTableReferenceIntoRouteTableReference(aaiRouteTableReference);
2198     }
2199
2200     protected void mapOwningEntity(List<AAIResultWrapper> owningEntities, ServiceInstance serviceInstance) {
2201         if (!owningEntities.isEmpty()) {
2202             AAIResultWrapper owningEntityWrapper = owningEntities.get(0);
2203             Optional<org.onap.aai.domain.yang.OwningEntity> aaiOwningEntityOp =
2204                     owningEntityWrapper.asBean(org.onap.aai.domain.yang.OwningEntity.class);
2205             if (aaiOwningEntityOp.isPresent()) {
2206                 OwningEntity owningEntity = this.mapperLayer.mapAAIOwningEntity(aaiOwningEntityOp.get());
2207                 serviceInstance.setOwningEntity(owningEntity);
2208             }
2209         }
2210     }
2211
2212     protected void mapProject(List<AAIResultWrapper> projects, ServiceInstance serviceInstance) {
2213         if (!projects.isEmpty()) {
2214             AAIResultWrapper projectWrapper = projects.get(0);
2215             Optional<org.onap.aai.domain.yang.Project> aaiProjectOp =
2216                     projectWrapper.asBean(org.onap.aai.domain.yang.Project.class);
2217             if (aaiProjectOp.isPresent()) {
2218                 Project project = this.mapperLayer.mapAAIProject(aaiProjectOp.get());
2219                 serviceInstance.setProject(project);
2220             }
2221         }
2222     }
2223
2224     protected Customer mapCustomer(String globalCustomerId, String subscriptionServiceType) {
2225         org.onap.aai.domain.yang.Customer aaiCustomer = this.bbInputSetupUtils.getAAICustomer(globalCustomerId);
2226         org.onap.aai.domain.yang.ServiceSubscription aaiServiceSubscription =
2227                 this.bbInputSetupUtils.getAAIServiceSubscription(globalCustomerId, subscriptionServiceType);
2228         Customer customer = this.mapperLayer.mapAAICustomer(aaiCustomer);
2229         ServiceSubscription serviceSubscription = this.mapperLayer.mapAAIServiceSubscription(aaiServiceSubscription);
2230         if (serviceSubscription != null) {
2231             customer.setServiceSubscription(serviceSubscription);
2232         }
2233         return customer;
2234     }
2235 }