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