repeat distribution transaction error
[so.git] / asdc-controller / src / main / java / org / onap / so / asdc / installer / heat / ToscaResourceInstaller.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.asdc.installer.heat;
25
26
27 import java.sql.Timestamp;
28 import java.util.ArrayList;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Optional;
36 import java.util.Set;
37 import java.util.stream.Collectors;
38 import org.hibernate.StaleObjectStateException;
39 import org.hibernate.exception.ConstraintViolationException;
40 import org.hibernate.exception.LockAcquisitionException;
41 import org.onap.sdc.api.notification.IArtifactInfo;
42 import org.onap.sdc.api.notification.IResourceInstance;
43 import org.onap.sdc.api.notification.IStatusData;
44 import org.onap.sdc.tosca.parser.api.IEntityDetails;
45 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
46 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
47 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
48 import org.onap.sdc.tosca.parser.enums.SdcTypes;
49 import org.onap.sdc.tosca.parser.impl.SdcPropertyNames;
50 import org.onap.sdc.toscaparser.api.CapabilityAssignment;
51 import org.onap.sdc.toscaparser.api.CapabilityAssignments;
52 import org.onap.sdc.toscaparser.api.Group;
53 import org.onap.sdc.toscaparser.api.NodeTemplate;
54 import org.onap.sdc.toscaparser.api.Policy;
55 import org.onap.sdc.toscaparser.api.Property;
56 import org.onap.sdc.toscaparser.api.RequirementAssignment;
57 import org.onap.sdc.toscaparser.api.RequirementAssignments;
58 import org.onap.sdc.toscaparser.api.elements.Metadata;
59 import org.onap.sdc.toscaparser.api.functions.GetInput;
60 import org.onap.sdc.toscaparser.api.parameters.Input;
61 import org.onap.sdc.utils.DistributionStatusEnum;
62 import org.onap.so.asdc.client.ASDCConfiguration;
63 import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
64 import org.onap.so.asdc.installer.ASDCElementInfo;
65 import org.onap.so.asdc.installer.BigDecimalVersion;
66 import org.onap.so.asdc.installer.IVfModuleData;
67 import org.onap.so.asdc.installer.PnfResourceStructure;
68 import org.onap.so.asdc.installer.ResourceStructure;
69 import org.onap.so.asdc.installer.ToscaResourceStructure;
70 import org.onap.so.asdc.installer.VfModuleArtifact;
71 import org.onap.so.asdc.installer.VfModuleStructure;
72 import org.onap.so.asdc.installer.VfResourceStructure;
73 import org.onap.so.asdc.installer.bpmn.WorkflowResource;
74 import org.onap.so.asdc.util.YamlEditor;
75 import org.onap.so.db.catalog.beans.AllottedResource;
76 import org.onap.so.db.catalog.beans.AllottedResourceCustomization;
77 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
78 import org.onap.so.db.catalog.beans.CollectionResource;
79 import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
80 import org.onap.so.db.catalog.beans.ConfigurationResource;
81 import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization;
82 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
83 import org.onap.so.db.catalog.beans.CvnfcCustomization;
84 import org.onap.so.db.catalog.beans.HeatEnvironment;
85 import org.onap.so.db.catalog.beans.HeatFiles;
86 import org.onap.so.db.catalog.beans.HeatTemplate;
87 import org.onap.so.db.catalog.beans.HeatTemplateParam;
88 import org.onap.so.db.catalog.beans.InstanceGroupType;
89 import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
90 import org.onap.so.db.catalog.beans.NetworkInstanceGroup;
91 import org.onap.so.db.catalog.beans.NetworkResource;
92 import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
93 import org.onap.so.db.catalog.beans.PnfResource;
94 import org.onap.so.db.catalog.beans.PnfResourceCustomization;
95 import org.onap.so.db.catalog.beans.Service;
96 import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization;
97 import org.onap.so.db.catalog.beans.SubType;
98 import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup;
99 import org.onap.so.db.catalog.beans.ToscaCsar;
100 import org.onap.so.db.catalog.beans.VFCInstanceGroup;
101 import org.onap.so.db.catalog.beans.VfModule;
102 import org.onap.so.db.catalog.beans.VfModuleCustomization;
103 import org.onap.so.db.catalog.beans.VnfResource;
104 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
105 import org.onap.so.db.catalog.beans.VnfcCustomization;
106 import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
107 import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository;
108 import org.onap.so.db.catalog.data.repository.AllottedResourceRepository;
109 import org.onap.so.db.catalog.data.repository.CollectionResourceCustomizationRepository;
110 import org.onap.so.db.catalog.data.repository.CollectionResourceRepository;
111 import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository;
112 import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository;
113 import org.onap.so.db.catalog.data.repository.CvnfcCustomizationRepository;
114 import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository;
115 import org.onap.so.db.catalog.data.repository.HeatTemplateRepository;
116 import org.onap.so.db.catalog.data.repository.InstanceGroupRepository;
117 import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository;
118 import org.onap.so.db.catalog.data.repository.NetworkResourceRepository;
119 import org.onap.so.db.catalog.data.repository.PnfCustomizationRepository;
120 import org.onap.so.db.catalog.data.repository.PnfResourceRepository;
121 import org.onap.so.db.catalog.data.repository.ServiceProxyResourceCustomizationRepository;
122 import org.onap.so.db.catalog.data.repository.ServiceRepository;
123 import org.onap.so.db.catalog.data.repository.TempNetworkHeatTemplateRepository;
124 import org.onap.so.db.catalog.data.repository.ToscaCsarRepository;
125 import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository;
126 import org.onap.so.db.catalog.data.repository.VFModuleRepository;
127 import org.onap.so.db.catalog.data.repository.VnfResourceRepository;
128 import org.onap.so.db.catalog.data.repository.VnfcCustomizationRepository;
129 import org.onap.so.db.catalog.data.repository.VnfcInstanceGroupCustomizationRepository;
130 import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus;
131 import org.onap.so.db.request.beans.WatchdogDistributionStatus;
132 import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup;
133 import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository;
134 import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository;
135 import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository;
136 import org.onap.so.logger.ErrorCode;
137 import org.onap.so.logger.MessageEnum;
138 import org.slf4j.Logger;
139 import org.slf4j.LoggerFactory;
140 import org.springframework.beans.factory.annotation.Autowired;
141 import org.springframework.orm.ObjectOptimisticLockingFailureException;
142 import org.springframework.stereotype.Component;
143 import org.springframework.transaction.annotation.Transactional;
144 import com.fasterxml.jackson.core.JsonProcessingException;
145 import com.fasterxml.jackson.databind.ObjectMapper;
146
147 @Component
148 public class ToscaResourceInstaller {
149
150     protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry";
151
152     protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor";
153
154     protected static final String ALLOTTED_RESOURCE = "Allotted Resource";
155
156     protected static final String MULTI_STAGE_DESIGN = "multi_stage_design";
157
158     protected static final String SCALABLE = "scalable";
159
160     protected static final String BASIC = "BASIC";
161
162     protected static final String PROVIDER = "PROVIDER";
163
164     protected static final String HEAT = "HEAT";
165
166     protected static final String MANUAL_RECORD = "MANUAL_RECORD";
167
168     protected static final String MSO = "SO";
169
170     protected static final String SDNC_MODEL_NAME = "sdnc_model_name";
171
172     protected static final String SDNC_MODEL_VERSION = "sdnc_model_version";
173
174     private static String CUSTOMIZATION_UUID = "customizationUUID";
175
176     protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration";
177
178     @Autowired
179     protected ServiceRepository serviceRepo;
180
181     @Autowired
182     protected InstanceGroupRepository instanceGroupRepo;
183
184     @Autowired
185     protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo;
186
187     @Autowired
188     protected CollectionResourceRepository collectionRepo;
189
190     @Autowired
191     protected CollectionResourceCustomizationRepository collectionCustomizationRepo;
192
193     @Autowired
194     protected ConfigurationResourceCustomizationRepository configCustomizationRepo;
195
196     @Autowired
197     protected ConfigurationResourceRepository configRepo;
198
199     @Autowired
200     protected VnfResourceRepository vnfRepo;
201
202     @Autowired
203     protected VFModuleRepository vfModuleRepo;
204
205     @Autowired
206     protected VFModuleCustomizationRepository vfModuleCustomizationRepo;
207
208     @Autowired
209     protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo;
210
211     @Autowired
212     protected VnfcCustomizationRepository vnfcCustomizationRepo;
213
214     @Autowired
215     protected CvnfcCustomizationRepository cvnfcCustomizationRepo;
216
217     @Autowired
218     protected AllottedResourceRepository allottedRepo;
219
220     @Autowired
221     protected AllottedResourceCustomizationRepository allottedCustomizationRepo;
222
223     @Autowired
224     protected NetworkResourceRepository networkRepo;
225
226     @Autowired
227     protected HeatTemplateRepository heatRepo;
228
229     @Autowired
230     protected NetworkResourceCustomizationRepository networkCustomizationRepo;
231
232     @Autowired
233     protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
234     @Autowired
235     protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
236     @Autowired
237     protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
238
239     @Autowired
240     protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo;
241
242     @Autowired
243     protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository;
244
245     @Autowired
246     protected ToscaCsarRepository toscaCsarRepo;
247
248     @Autowired
249     protected PnfResourceRepository pnfResourceRepository;
250
251     @Autowired
252     protected PnfCustomizationRepository pnfCustomizationRepository;
253
254     @Autowired
255     protected WorkflowResource workflowResource;
256
257     protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class);
258
259     public boolean isCsarAlreadyDeployed(ToscaResourceStructure toscaResourceStructure)
260             throws ArtifactInstallerException {
261         boolean deployed = false;
262         if (toscaResourceStructure == null) {
263             return deployed;
264         }
265
266         IArtifactInfo inputToscaCsar = toscaResourceStructure.getToscaArtifact();
267         String checkSum = inputToscaCsar.getArtifactChecksum();
268         String artifactUuid = inputToscaCsar.getArtifactUUID();
269
270         Optional<ToscaCsar> toscaCsarObj = toscaCsarRepo.findById(artifactUuid);
271         if (toscaCsarObj.isPresent()) {
272             ToscaCsar toscaCsar = toscaCsarObj.get();
273             if (!toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
274                 String errorMessage =
275                         String.format("Csar with UUID: %s already exists.Their checksums don't match", artifactUuid);
276                 throw new ArtifactInstallerException(errorMessage);
277             } else if (toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
278                 deployed = true;
279             }
280         }
281         return deployed;
282     }
283
284     public boolean isResourceAlreadyDeployed(ResourceStructure vfResourceStruct, boolean serviceDeployed)
285             throws ArtifactInstallerException {
286         boolean status = false;
287         ResourceStructure vfResourceStructure = vfResourceStruct;
288         try {
289             status = vfResourceStructure.isDeployedSuccessfully();
290         } catch (RuntimeException e) {
291             status = false;
292         }
293         try {
294             Service existingService =
295                     serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID());
296             if (existingService != null && !serviceDeployed)
297                 status = true;
298             if (status) {
299                 logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
300                         vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
301                         vfResourceStructure.getNotification().getServiceName(),
302                         BigDecimalVersion.castAndCheckNotificationVersionToString(
303                                 vfResourceStructure.getNotification().getServiceVersion()),
304                         vfResourceStructure.getNotification().getServiceUUID(),
305                         vfResourceStructure.getResourceInstance().getResourceName(), "", "");
306                 WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(
307                         vfResourceStruct.getNotification().getDistributionID(), MSO);
308                 wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
309                 watchdogCDStatusRepository.saveAndFlush(wdStatus);
310             } else {
311                 logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
312                         vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
313                         vfResourceStructure.getNotification().getServiceName(),
314                         BigDecimalVersion.castAndCheckNotificationVersionToString(
315                                 vfResourceStructure.getNotification().getServiceVersion()),
316                         vfResourceStructure.getNotification().getServiceUUID(),
317                         vfResourceStructure.getResourceInstance().getResourceName(), "", "");
318             }
319             return status;
320         } catch (Exception e) {
321             logger.error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), ErrorCode.SchemaError.getValue(),
322                     "Exception - isResourceAlreadyDeployed");
323             throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e);
324         }
325     }
326
327     public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException {
328         logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}",
329                 iStatus.getDistributionID(), iStatus.getComponentName());
330
331         try {
332             WatchdogComponentDistributionStatus cdStatus =
333                     new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), iStatus.getComponentName());
334             cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString());
335             watchdogCDStatusRepository.save(cdStatus);
336
337         } catch (Exception e) {
338             logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage());
339             throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage());
340         }
341     }
342
343
344     @Transactional(rollbackFor = {ArtifactInstallerException.class})
345     public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct)
346             throws ArtifactInstallerException {
347         if (resourceStruct instanceof VfResourceStructure) {
348             installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct);
349         } else if (resourceStruct instanceof PnfResourceStructure) {
350             installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct);
351         } else {
352             logger.warn("Unrecognized resource type");
353         }
354     }
355
356     private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct)
357             throws ArtifactInstallerException {
358
359         // PCLO: in case of deployment failure, use a string that will represent
360         // the type of artifact that failed...
361         List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
362         try {
363             createToscaCsar(toscaResourceStruct);
364             Service service = createService(toscaResourceStruct, resourceStruct);
365
366             processResourceSequence(toscaResourceStruct, service);
367             processPnfResources(toscaResourceStruct, service, resourceStruct);
368             serviceRepo.save(service);
369
370             WatchdogComponentDistributionStatus status =
371                     new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
372             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
373             watchdogCDStatusRepository.save(status);
374
375             toscaResourceStruct.setSuccessfulDeployment();
376
377         } catch (Exception e) {
378             logger.debug("Exception :", e);
379             WatchdogComponentDistributionStatus status =
380                     new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
381             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
382             watchdogCDStatusRepository.save(status);
383             Throwable dbExceptionToCapture = e;
384             while (!(dbExceptionToCapture instanceof ConstraintViolationException
385                     || dbExceptionToCapture instanceof LockAcquisitionException)
386                     && (dbExceptionToCapture.getCause() != null)) {
387                 dbExceptionToCapture = dbExceptionToCapture.getCause();
388             }
389
390             if (dbExceptionToCapture instanceof ConstraintViolationException
391                     || dbExceptionToCapture instanceof LockAcquisitionException) {
392                 logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
393                         resourceStruct.getResourceInstance().getResourceName(),
394                         resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
395                         "Exception - ASCDC Artifact already deployed", e);
396             } else {
397                 String elementToLog = (!artifactListForLogging.isEmpty()
398                         ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
399                         : "No element listed");
400                 logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
401                         ErrorCode.DataError.getValue(), "Exception caught during installation of "
402                                 + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback",
403                         e);
404                 throw new ArtifactInstallerException(
405                         "Exception caught during installation of "
406                                 + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.",
407                         e);
408             }
409         }
410     }
411
412     @Transactional(rollbackFor = {ArtifactInstallerException.class})
413     public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct)
414             throws ArtifactInstallerException {
415         VfResourceStructure vfResourceStructure = vfResourceStruct;
416         extractHeatInformation(toscaResourceStruct, vfResourceStructure);
417
418         // PCLO: in case of deployment failure, use a string that will represent
419         // the type of artifact that failed...
420         List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
421         try {
422             createToscaCsar(toscaResourceStruct);
423             createService(toscaResourceStruct, vfResourceStruct);
424             Service service = toscaResourceStruct.getCatalogService();
425             List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList();
426
427             for (NodeTemplate nodeTemplate : vfNodeTemplatesList) {
428                 Metadata metadata = nodeTemplate.getMetaData();
429                 String serviceType = toscaResourceStruct.getCatalogService().getServiceType();
430                 String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper()
431                         .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY);
432                 processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata,
433                         vfCustomizationCategory);
434             }
435
436             workflowResource.processWorkflows(vfResourceStructure);
437             processResourceSequence(toscaResourceStruct, service);
438             List<NodeTemplate> allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources();
439             processAllottedResources(toscaResourceStruct, service, allottedResourceList);
440             processNetworks(toscaResourceStruct, service);
441             // process Network Collections
442             processNetworkCollections(toscaResourceStruct, service);
443             // Process Service Proxy & Configuration
444             processServiceProxyAndConfiguration(toscaResourceStruct, service);
445
446             logger.info("Saving Service: {} ", service.getModelName());
447             service = serviceRepo.save(service);
448             correlateConfigCustomResources(service);
449
450             WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
451                     vfResourceStruct.getNotification().getDistributionID(), MSO);
452             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
453             watchdogCDStatusRepository.save(status);
454
455             toscaResourceStruct.setSuccessfulDeployment();
456
457         } catch (Exception e) {
458             logger.debug("Exception :", e);
459             WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(
460                     vfResourceStruct.getNotification().getDistributionID(), MSO);
461             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
462             watchdogCDStatusRepository.save(status);
463             Throwable dbExceptionToCapture = e;
464             while (!(dbExceptionToCapture instanceof ConstraintViolationException
465                     || dbExceptionToCapture instanceof LockAcquisitionException)
466                     && (dbExceptionToCapture.getCause() != null)) {
467                 dbExceptionToCapture = dbExceptionToCapture.getCause();
468             }
469
470             if (dbExceptionToCapture instanceof ConstraintViolationException
471                     || dbExceptionToCapture instanceof LockAcquisitionException) {
472                 logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
473                         vfResourceStructure.getResourceInstance().getResourceName(),
474                         vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
475                         "Exception - ASCDC Artifact already deployed", e);
476             } else {
477                 String elementToLog = (!artifactListForLogging.isEmpty()
478                         ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
479                         : "No element listed");
480                 logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
481                         ErrorCode.DataError.getValue(),
482                         "Exception caught during installation of "
483                                 + vfResourceStructure.getResourceInstance().getResourceName()
484                                 + ". Transaction rollback",
485                         e);
486                 throw new ArtifactInstallerException("Exception caught during installation of "
487                         + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e);
488             }
489         }
490     }
491
492
493     List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates,
494             ISdcCsarHelper iSdcCsarHelper) {
495
496         List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
497         nodes.addAll(nodeTemplates);
498
499         for (NodeTemplate nodeTemplate : nodeTemplates) {
500             RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
501             List<RequirementAssignment> reqAs = requirement.getAll();
502             for (RequirementAssignment ra : reqAs) {
503                 String reqNode = ra.getNodeTemplateName();
504                 for (NodeTemplate rNode : resultList) {
505                     if (rNode.getName().equals(reqNode)) {
506                         if (!resultList.contains(nodeTemplate)) {
507                             resultList.add(nodeTemplate);
508                         }
509                         if (nodes.contains(nodeTemplate)) {
510                             nodes.remove(nodeTemplate);
511                         }
512                         break;
513                     }
514                 }
515             }
516         }
517
518         if (!nodes.isEmpty()) {
519             getRequirementList(resultList, nodes, iSdcCsarHelper);
520         }
521
522         return resultList;
523     }
524
525     // This method retrieve resource sequence from csar file
526     void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) {
527         List<String> resouceSequence = new ArrayList<String>();
528         List<NodeTemplate> resultList = new ArrayList<NodeTemplate>();
529
530         ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
531         List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates();
532         List<NodeTemplate> nodes = new ArrayList<NodeTemplate>();
533         nodes.addAll(nodeTemplates);
534
535         for (NodeTemplate nodeTemplate : nodeTemplates) {
536             RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate);
537
538             if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) {
539                 resultList.add(nodeTemplate);
540                 nodes.remove(nodeTemplate);
541             }
542         }
543
544         resultList = getRequirementList(resultList, nodes, iSdcCsarHelper);
545
546         for (NodeTemplate node : resultList) {
547             String templateName = node.getMetaData().getValue("name");
548             if (!resouceSequence.contains(templateName)) {
549                 resouceSequence.add(templateName);
550             }
551         }
552
553         String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(","));
554         service.setResourceOrder(resourceSeqStr);
555         logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr);
556     }
557
558     private static String getValue(Object value, List<Input> servInputs) {
559         String output = null;
560         if (value instanceof Map) {
561             // currently this logic handles only one level of nesting.
562             return ((LinkedHashMap) value).values().toArray()[0].toString();
563         } else if (value instanceof GetInput) {
564             String inputName = ((GetInput) value).getInputName();
565
566             for (Input input : servInputs) {
567                 if (input.getName().equals(inputName)) {
568                     // keep both input name and default value
569                     // if service input does not supplies value the use default value
570                     String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : "";
571                     output = inputName + "|" + defaultValue;// return default value
572                 }
573             }
574
575         } else {
576             output = value != null ? value.toString() : "";
577         }
578         return output; // return property value
579     }
580
581     String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid)
582             throws ArtifactInstallerException {
583         Map<String, String> resouceRequest = new HashMap<>();
584         ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
585
586         List<Input> serInput = iSdcCsarHelper.getServiceInputs();
587         Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream()
588                 .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid))
589                 .findFirst();
590         if (nodeTemplateOpt.isPresent()) {
591             NodeTemplate nodeTemplate = nodeTemplateOpt.get();
592             LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties();
593
594             for (String key : resourceProperties.keySet()) {
595                 Property property = resourceProperties.get(key);
596
597                 String value = getValue(property.getValue(), serInput);
598                 resouceRequest.put(key, value);
599             }
600         }
601
602         try {
603             ObjectMapper objectMapper = new ObjectMapper();
604             String jsonStr = objectMapper.writeValueAsString(resouceRequest);
605
606             jsonStr = jsonStr.replace("\"", "\\\"");
607             logger.debug(
608                     "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr);
609             return jsonStr;
610         } catch (JsonProcessingException e) {
611             logger.error("resource input could not be deserialized for resource customization id ("
612                     + resourceCustomizationUuid + ")");
613             throw new ArtifactInstallerException("resource input could not be parsed", e);
614         }
615     }
616
617     protected void processNetworks(ToscaResourceStructure toscaResourceStruct, Service service)
618             throws ArtifactInstallerException {
619         List<NodeTemplate> nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper().getServiceVlList();
620
621         if (nodeTemplatesVLList != null) {
622             for (NodeTemplate vlNode : nodeTemplatesVLList) {
623                 String networkResourceModelName = vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME);
624
625                 TempNetworkHeatTemplateLookup tempNetworkLookUp =
626                         tempNetworkLookupRepo.findFirstBynetworkResourceModelName(networkResourceModelName);
627
628                 if (tempNetworkLookUp != null) {
629                     HeatTemplate heatTemplate =
630                             heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
631                     if (heatTemplate != null) {
632                         NetworkResourceCustomization networkCustomization = createNetwork(vlNode, toscaResourceStruct,
633                                 heatTemplate, tempNetworkLookUp.getAicVersionMax(),
634                                 tempNetworkLookUp.getAicVersionMin(), service);
635                         service.getNetworkCustomizations().add(networkCustomization);
636                     } else {
637                         throw new ArtifactInstallerException("No HeatTemplate found for artifactUUID: "
638                                 + tempNetworkLookUp.getHeatTemplateArtifactUuid());
639                     }
640                 } else {
641                     NetworkResourceCustomization networkCustomization =
642                             createNetwork(vlNode, toscaResourceStruct, null, null, null, service);
643                     service.getNetworkCustomizations().add(networkCustomization);
644                     logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for "
645                             + networkResourceModelName);
646                 }
647
648             }
649         }
650     }
651
652     protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service,
653             List<NodeTemplate> allottedResourceList) {
654         if (allottedResourceList != null) {
655             for (NodeTemplate allottedNode : allottedResourceList) {
656                 service.getAllottedCustomizations()
657                         .add(createAllottedResource(allottedNode, toscaResourceStruct, service));
658             }
659         }
660     }
661
662
663     protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) {
664         Metadata metadata = nodeTemplate.getMetaData();
665         ConfigurationResource configResource = new ConfigurationResource();
666         configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
667         configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
668         configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
669         configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
670         configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
671         configResource.setToscaNodeType(nodeTemplate.getType());
672         return configResource;
673     }
674
675     protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate,
676             ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
677             Service service) {
678         Metadata metadata = nodeTemplate.getMetaData();
679
680         ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
681
682         ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization();
683
684         Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
685
686         configCustomizationResource
687                 .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
688         configCustomizationResource.setModelInstanceName(nodeTemplate.getName());
689
690         configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper()
691                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
692         configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper()
693                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE));
694         configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper()
695                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
696         configCustomizationResource
697                 .setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID());
698
699         configCustomizationResource.setConfigurationResource(configResource);
700         configCustomizationResource.setService(service);
701         configResourceCustomizationSet.add(configCustomizationResource);
702
703         configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
704
705         return configCustomizationResource;
706     }
707
708
709     protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) {
710
711         List<NodeTemplate> serviceProxyResourceList =
712                 toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY);
713
714         List<NodeTemplate> configurationNodeTemplatesList =
715                 toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);
716
717         List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>();
718         List<ConfigurationResourceCustomization> configurationResourceList =
719                 new ArrayList<ConfigurationResourceCustomization>();
720
721         ServiceProxyResourceCustomization serviceProxy = null;
722
723         if (serviceProxyResourceList != null) {
724             for (NodeTemplate spNode : serviceProxyResourceList) {
725                 serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct);
726                 serviceProxyList.add(serviceProxy);
727
728                 for (NodeTemplate configNode : configurationNodeTemplatesList) {
729
730                     List<RequirementAssignment> requirementsList =
731                             toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll();
732                     for (RequirementAssignment requirement : requirementsList) {
733                         if (requirement.getNodeTemplateName().equals(spNode.getName())) {
734                             ConfigurationResourceCustomization configurationResource =
735                                     createConfiguration(configNode, toscaResourceStruct, serviceProxy, service);
736
737                             Optional<ConfigurationResourceCustomization> matchingObject =
738                                     configurationResourceList.stream()
739                                             .filter(configurationResourceCustomization -> configNode.getMetaData()
740                                                     .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)
741                                                     .equals(configurationResource.getModelCustomizationUUID()))
742                                             .filter(configurationResourceCustomization -> configurationResourceCustomization
743                                                     .getModelInstanceName()
744                                                     .equals(configurationResource.getModelInstanceName()))
745                                             .findFirst();
746                             if (!matchingObject.isPresent()) {
747                                 configurationResourceList.add(configurationResource);
748                             }
749                             break;
750                         }
751                     }
752                 }
753
754             }
755         }
756
757         service.setConfigurationCustomizations(configurationResourceList);
758         service.setServiceProxyCustomizations(serviceProxyList);
759     }
760
761     /*
762      * ConfigurationResourceCustomization objects have their IDs auto incremented in the database. Unless we know their
763      * IDs we cannot possibly associate their related records. So these ConfigResourceCustomizations are persisted first
764      * and subsequently correlated.
765      */
766
767     protected void correlateConfigCustomResources(Service service) {
768         /* Assuming that we have only one pair of VRF-VNR */
769         ConfigurationResourceCustomization vrfConfigCustomResource = null;
770         ConfigurationResourceCustomization vnrConfigCustomResource = null;
771         List<ConfigurationResourceCustomization> configCustomList = service.getConfigurationCustomizations();
772         for (ConfigurationResourceCustomization configResource : configCustomList) {
773             String nodeType = configResource.getConfigurationResource().getToscaNodeType();
774             if (NODES_VRF_ENTRY.equalsIgnoreCase(nodeType)) {
775                 vrfConfigCustomResource = configResource;
776             } else if (VLAN_NETWORK_RECEPTOR.equalsIgnoreCase(nodeType)) {
777                 vnrConfigCustomResource = configResource;
778             }
779         }
780
781         if (vrfConfigCustomResource != null) {
782             vrfConfigCustomResource.setConfigResourceCustomization(vnrConfigCustomResource);
783             configCustomizationRepo.save(vrfConfigCustomResource);
784
785         }
786         if (vnrConfigCustomResource != null) {
787             vnrConfigCustomResource.setConfigResourceCustomization(vrfConfigCustomResource);
788             configCustomizationRepo.save(vnrConfigCustomResource);
789         }
790     }
791
792     protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) {
793
794         List<NodeTemplate> networkCollectionList =
795                 toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR);
796
797         if (networkCollectionList != null) {
798             for (NodeTemplate crNode : networkCollectionList) {
799
800                 createNetworkCollection(crNode, toscaResourceStruct, service);
801                 collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource());
802
803                 List<NetworkInstanceGroup> networkInstanceGroupList =
804                         toscaResourceStruct.getCatalogNetworkInstanceGroup();
805                 for (NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList) {
806                     instanceGroupRepo.saveAndFlush(networkInstanceGroup);
807                 }
808
809             }
810         }
811         service.getCollectionResourceCustomizations()
812                 .add(toscaResourceStruct.getCatalogCollectionResourceCustomization());
813     }
814
815
816
817     /**
818      * This is used to process the PNF specific resource, including resource and resource_customization.
819      * {@link IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for
820      * details.
821      */
822     protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service,
823             PnfResourceStructure resourceStructure) throws Exception {
824         logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID());
825
826         ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper();
827         EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build();
828         TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build();
829
830         List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false);
831         for (IEntityDetails entityDetails : entityDetailsList) {
832             Metadata metadata = entityDetails.getMetadata();
833             String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
834             String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
835             String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID();
836             if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) {
837                 logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}",
838                         customizationUUID, notifCustomizationUUID);
839
840                 if (checkExistingPnfResourceCutomization(customizationUUID)) {
841                     logger.info("Resource customization UUID: {} already deployed", customizationUUID);
842                 } else {
843                     PnfResource pnfResource = findExistingPnfResource(service, modelUuid);
844                     if (pnfResource == null) {
845                         pnfResource = createPnfResource(entityDetails);
846                     }
847                     PnfResourceCustomization pnfResourceCustomization =
848                             createPnfResourceCustomization(entityDetails, pnfResource);
849                     pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization);
850                     toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization);
851                     service.getPnfCustomizations().add(pnfResourceCustomization);
852                 }
853             } else {
854                 logger.warn(
855                         "Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}",
856                         customizationUUID, notifCustomizationUUID);
857             }
858         }
859     }
860
861     private PnfResource findExistingPnfResource(Service service, String modelUuid) {
862         PnfResource pnfResource = null;
863         for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) {
864             if (pnfResourceCustomization.getPnfResources() != null
865                     && pnfResourceCustomization.getPnfResources().getModelUUID().equals(modelUuid)) {
866                 pnfResource = pnfResourceCustomization.getPnfResources();
867             }
868         }
869         if (pnfResource == null) {
870             pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource);
871         }
872         return pnfResource;
873     }
874
875     private boolean checkExistingPnfResourceCutomization(String customizationUUID) {
876         return pnfCustomizationRepository.findById(customizationUUID).isPresent();
877     }
878
879     /**
880      * Construct the {@link PnfResource} from {@link IEntityDetails} object.
881      */
882     private PnfResource createPnfResource(IEntityDetails entity) {
883         PnfResource pnfResource = new PnfResource();
884         Metadata metadata = entity.getMetadata();
885         pnfResource.setModelInvariantUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
886         pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
887         pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
888         pnfResource.setModelVersion(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
889         pnfResource.setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
890         pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)));
891         pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
892         pnfResource.setToscaNodeType(entity.getToscaType());
893         return pnfResource;
894     }
895
896     /**
897      * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object.
898      */
899     private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails,
900             PnfResource pnfResource) {
901
902         PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization();
903         Metadata metadata = entityDetails.getMetadata();
904         Map<String, Property> properties = entityDetails.getProperties();
905         pnfResourceCustomization.setModelCustomizationUUID(
906                 testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
907         pnfResourceCustomization.setModelInstanceName(entityDetails.getName());
908         pnfResourceCustomization
909                 .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
910         pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE)));
911         pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE)));
912         pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
913         pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN)));
914         pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME)));
915         pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION)));
916         pnfResourceCustomization.setSkipPostInstConf(getBooleanValue(properties.get(SKIP_POST_INST_CONF)));
917         pnfResourceCustomization.setPnfResources(pnfResource);
918
919         return pnfResourceCustomization;
920     }
921
922     /**
923      * Get value from {@link Property} and cast to boolean value. Return true if property is null.
924      */
925     private boolean getBooleanValue(Property property) {
926         if (null == property) {
927             return true;
928         }
929         Object value = property.getValue();
930         return new Boolean(String.valueOf(value));
931     }
932
933     /**
934      * Get value from {@link Property} and cast to String value. Return empty String if property is null value.
935      */
936     private String getStringValue(Property property) {
937         if (null == property) {
938             return "";
939         }
940         Object value = property.getValue();
941         return String.valueOf(value);
942     }
943
944     protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure,
945             Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory)
946             throws Exception {
947
948         logger.debug("VF Category is : " + vfCustomizationCategory);
949
950         if (vfResourceStructure.getVfModuleStructure() != null
951                 && !vfResourceStructure.getVfModuleStructure().isEmpty()) {
952
953             String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper().getMetadataPropertyValue(metadata,
954                     SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
955             logger.debug("VFCustomizationUUID=" + vfCustomizationUUID);
956
957             IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
958
959             // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before
960             // comparing their VF Modules UUID's
961             logger.debug("Checking if Notification VF ResourceCustomizationUUID: "
962                     + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: "
963                     + vfCustomizationUUID);
964
965             if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {
966
967                 logger.debug("vfCustomizationUUID: " + vfCustomizationUUID
968                         + " matches vfNotificationResource CustomizationUUID");
969
970                 VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service);
971
972                 Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>();
973                 Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>();
974
975                 for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) {
976
977                     logger.debug("vfModuleStructure:" + vfModuleStructure.toString());
978                     List<org.onap.sdc.toscaparser.api.Group> vfGroups =
979                             toscaResourceStruct.getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID);
980                     IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata();
981
982                     logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : "
983                             + vfMetadata.getVfModuleModelCustomizationUUID());
984
985                     Optional<org.onap.sdc.toscaparser.api.Group> matchingObject = vfGroups.stream()
986                             .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID "
987                                     + group.getMetadata().getValue("vfModuleModelCustomizationUUID")))
988                             .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID")
989                                     .equals(vfMetadata.getVfModuleModelCustomizationUUID()))
990                             .findFirst();
991                     if (matchingObject.isPresent()) {
992                         VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(),
993                                 nodeTemplate, toscaResourceStruct, vfResourceStructure, vfMetadata, vnfResource,
994                                 service, existingCvnfcSet, existingVnfcSet);
995                         vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources());
996                     } else
997                         throw new Exception(
998                                 "Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: "
999                                         + vfMetadata.getVfModuleModelCustomizationUUID());
1000
1001                 }
1002
1003
1004                 // Check for VNFC Instance Group info and add it if there is
1005                 List<Group> groupList =
1006                         toscaResourceStruct.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
1007                                 nodeTemplate, "org.openecomp.groups.VfcInstanceGroup");
1008
1009                 for (Group group : groupList) {
1010                     VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization =
1011                             createVNFCInstanceGroup(nodeTemplate, group, vnfResource, toscaResourceStruct);
1012                     vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
1013                 }
1014
1015
1016                 service.getVnfCustomizations().add(vnfResource);
1017             } else {
1018                 logger.debug("Notification VF ResourceCustomizationUUID: "
1019                         + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
1020                         + "Tosca VF Customization UUID: " + vfCustomizationUUID);
1021             }
1022         }
1023     }
1024
1025     public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification,
1026             String consumerId) {
1027         WatchdogServiceModVerIdLookup modVerIdLookup =
1028                 new WatchdogServiceModVerIdLookup(distributionId, servideUUID, distributionNotification, consumerId);
1029         watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup);
1030
1031         try {
1032
1033             WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId);
1034             watchdogDistributionStatusRepository.saveAndFlush(distributionStatus);
1035
1036         } catch (ObjectOptimisticLockingFailureException e) {
1037             logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString());
1038             throw e;
1039         }
1040     }
1041
1042     protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct,
1043             VfResourceStructure vfResourceStructure) {
1044         for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1045
1046             switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) {
1047                 case ASDCConfiguration.HEAT:
1048                 case ASDCConfiguration.HEAT_NESTED:
1049                     createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
1050                     break;
1051                 case ASDCConfiguration.HEAT_VOL:
1052                     createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
1053                     VfModuleArtifact envModuleArtifact =
1054                             getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
1055                     createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact);
1056                     break;
1057                 case ASDCConfiguration.HEAT_ENV:
1058                     createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact);
1059                     break;
1060                 case ASDCConfiguration.HEAT_ARTIFACT:
1061                     createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, toscaResourceStruct);
1062                     break;
1063                 case ASDCConfiguration.HEAT_NET:
1064                 case ASDCConfiguration.OTHER:
1065                     logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(),
1066                             vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:"
1067                                     + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")",
1068                             ErrorCode.DataError.getValue(), "Artifact type not supported");
1069                     break;
1070                 default:
1071                     break;
1072
1073             }
1074         }
1075     }
1076
1077     protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure,
1078             VfModuleArtifact vfModuleArtifact) {
1079         String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName();
1080         artifactName = artifactName.substring(0, artifactName.indexOf('.'));
1081         for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1082             if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName)
1083                     && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
1084                 return moduleArtifact;
1085             }
1086         }
1087         return null;
1088     }
1089
1090     public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure,
1091             List<String> listTypes) {
1092         String newFileBody = filebody;
1093         for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1094
1095             if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) {
1096
1097                 newFileBody =
1098                         verifyTheFilePrefixInString(newFileBody, moduleArtifact.getArtifactInfo().getArtifactName());
1099             }
1100         }
1101         return newFileBody;
1102     }
1103
1104     public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) {
1105
1106         String needlePrefix = "file:///";
1107         String prefixedFilenameToVerify = needlePrefix + filenameToVerify;
1108
1109         if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) {
1110             return body;
1111         }
1112
1113         StringBuilder sb = new StringBuilder(body.length());
1114
1115         int currentIndex = 0;
1116         int startIndex = 0;
1117
1118         while (currentIndex != -1) {
1119             startIndex = currentIndex;
1120             currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex);
1121
1122             if (currentIndex == -1) {
1123                 break;
1124             }
1125             // We append from the startIndex up to currentIndex (start of File
1126             // Name)
1127             sb.append(body.substring(startIndex, currentIndex));
1128             sb.append(filenameToVerify);
1129
1130             currentIndex += prefixedFilenameToVerify.length();
1131         }
1132
1133         sb.append(body.substring(startIndex));
1134
1135         return sb.toString();
1136     }
1137
1138     protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,
1139             ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) {
1140         HeatTemplate heatTemplate = new HeatTemplate();
1141         List<String> typeList = new ArrayList<>();
1142         typeList.add(ASDCConfiguration.HEAT_NESTED);
1143         typeList.add(ASDCConfiguration.HEAT_ARTIFACT);
1144
1145         heatTemplate.setTemplateBody(
1146                 verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
1147         heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1148
1149         if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
1150             heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
1151         } else {
1152             heatTemplate.setTimeoutMinutes(240);
1153         }
1154
1155         heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1156         heatTemplate.setVersion(BigDecimalVersion
1157                 .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1158         heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1159
1160         if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1161             heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1162         } else {
1163             heatTemplate.setArtifactChecksum(MANUAL_RECORD);
1164         }
1165
1166         Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(),
1167                 vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1168         heatTemplate.setParameters(heatParam);
1169         vfModuleArtifact.setHeatTemplate(heatTemplate);
1170     }
1171
1172     protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure,
1173             VfModuleArtifact vfModuleArtifact) {
1174         HeatEnvironment heatEnvironment = new HeatEnvironment();
1175         heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1176         List<String> typeList = new ArrayList<>();
1177         typeList.add(ASDCConfiguration.HEAT);
1178         typeList.add(ASDCConfiguration.HEAT_VOL);
1179         heatEnvironment.setEnvironment(
1180                 verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
1181         heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1182         heatEnvironment.setVersion(BigDecimalVersion
1183                 .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1184         heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1185
1186         if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1187             heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1188         } else {
1189             heatEnvironment.setArtifactChecksum(MANUAL_RECORD);
1190         }
1191         vfModuleArtifact.setHeatEnvironment(heatEnvironment);
1192     }
1193
1194     protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure,
1195             VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) {
1196
1197         HeatFiles heatFile = new HeatFiles();
1198         heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1199         heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1200         heatFile.setFileBody(vfModuleArtifact.getResult());
1201         heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1202         heatFile.setVersion(BigDecimalVersion
1203                 .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1204         toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1205         if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1206             heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1207         } else {
1208             heatFile.setArtifactChecksum(MANUAL_RECORD);
1209         }
1210         vfModuleArtifact.setHeatFiles(heatFile);
1211     }
1212
1213     protected Service createService(ToscaResourceStructure toscaResourceStructure,
1214             ResourceStructure resourceStructure) {
1215
1216         Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata();
1217
1218         Service service = new Service();
1219
1220         if (serviceMetadata != null) {
1221
1222             if (toscaResourceStructure.getServiceVersion() != null) {
1223                 service.setModelVersion(toscaResourceStructure.getServiceVersion());
1224             }
1225
1226             service.setServiceType(serviceMetadata.getValue("serviceType"));
1227             service.setServiceRole(serviceMetadata.getValue("serviceRole"));
1228             service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
1229
1230             service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1231             service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1232             service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1233             service.setEnvironmentContext(serviceMetadata.getValue("environmentContext"));
1234
1235             if (resourceStructure != null)
1236                 service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext());
1237
1238             service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1239             service.setCsar(toscaResourceStructure.getCatalogToscaCsar());
1240         }
1241
1242
1243         toscaResourceStructure.setCatalogService(service);
1244         return service;
1245     }
1246
1247     protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service,
1248             ToscaResourceStructure toscaResourceStructure) {
1249
1250         Metadata spMetadata = nodeTemplate.getMetaData();
1251
1252         ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization();
1253
1254         Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>();
1255
1256         spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1257         spCustomizationResource
1258                 .setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1259         spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1260         spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1261         spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1262
1263         spCustomizationResource
1264                 .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1265         spCustomizationResource.setModelInstanceName(nodeTemplate.getName());
1266         spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
1267
1268         String sourceServiceUUID = spMetadata.getValue("sourceModelUuid");
1269
1270         Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID);
1271
1272         spCustomizationResource.setSourceService(sourceService);
1273         spCustomizationResource.setToscaNodeType(nodeTemplate.getType());
1274         serviceProxyCustomizationSet.add(spCustomizationResource);
1275
1276
1277         toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource);
1278
1279         return spCustomizationResource;
1280     }
1281
1282     protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate,
1283             ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
1284             Service service) {
1285
1286         ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization(
1287                 nodeTemplate, toscaResourceStructure, spResourceCustomization, service);
1288
1289         ConfigurationResource configResource = getConfigurationResource(nodeTemplate);
1290
1291         Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>();
1292
1293         configCustomizationResource.setConfigurationResource(configResource);
1294
1295         configResourceCustomizationSet.add(configCustomizationResource);
1296
1297         configResource.setConfigurationResourceCustomization(configResourceCustomizationSet);
1298
1299         toscaResourceStructure.setCatalogConfigurationResource(configResource);
1300
1301         toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource);
1302
1303         return configCustomizationResource;
1304     }
1305
1306     protected ConfigurationResource createFabricConfiguration(NodeTemplate nodeTemplate,
1307             ToscaResourceStructure toscaResourceStructure) {
1308
1309         Metadata fabricMetadata = nodeTemplate.getMetaData();
1310
1311         ConfigurationResource configResource = new ConfigurationResource();
1312
1313         configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1314         configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1315         configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1316         configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1317         configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1318         configResource.setToscaNodeType(nodeTemplate.getType());
1319
1320         return configResource;
1321     }
1322
1323     protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) {
1324         ToscaCsar toscaCsar = new ToscaCsar();
1325         if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) {
1326             toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum());
1327         } else {
1328             toscaCsar.setArtifactChecksum(MANUAL_RECORD);
1329         }
1330         toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
1331         toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName());
1332         toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion());
1333         toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription());
1334         toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL());
1335
1336         toscaResourceStructure.setCatalogToscaCsar(toscaCsar);
1337     }
1338
1339     protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) {
1340         VnfcCustomization vnfcCustomization = null;
1341         for (VnfcCustomization vnfcCustom : vnfcCustomizations) {
1342             if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
1343                 vnfcCustomization = vnfcCustom;
1344             }
1345         }
1346
1347         if (vnfcCustomization == null)
1348             vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
1349         // vnfcCustomization = new VnfcCustomization();
1350
1351         return vnfcCustomization;
1352     }
1353
1354     protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations,
1355             String customizationUUID) {
1356         CvnfcCustomization cvnfcCustomization = null;
1357         for (CvnfcCustomization cvnfcCustom : cvnfcCustomizations) {
1358             if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
1359                 cvnfcCustomization = cvnfcCustom;
1360             }
1361         }
1362
1363         if (cvnfcCustomization == null)
1364             cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
1365
1366         return cvnfcCustomization;
1367     }
1368
1369     protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate,
1370             ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,
1371             Service service) {
1372
1373         NetworkResourceCustomization networkResourceCustomization =
1374                 networkCustomizationRepo.findOneByModelCustomizationUUID(
1375                         networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1376
1377         boolean networkUUIDsMatch = true;
1378         // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from
1379         // the distribution.
1380         // If not we'll update the Customization record with latest from the distribution
1381         if (networkResourceCustomization != null) {
1382             String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID();
1383             String latestNetworkModelUUID =
1384                     networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
1385
1386             if (!existingNetworkModelUUID.equals(latestNetworkModelUUID)) {
1387                 networkUUIDsMatch = false;
1388             }
1389
1390         }
1391
1392         if (networkResourceCustomization != null && !networkUUIDsMatch) {
1393
1394             NetworkResource networkResource =
1395                     createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, aicMax, aicMin);
1396
1397             networkResourceCustomization.setNetworkResource(networkResource);
1398
1399             networkCustomizationRepo.saveAndFlush(networkResourceCustomization);
1400
1401
1402         } else if (networkResourceCustomization == null) {
1403             networkResourceCustomization =
1404                     createNetworkResourceCustomization(networkNodeTemplate, toscaResourceStructure);
1405
1406             NetworkResource networkResource = findExistingNetworkResource(service,
1407                     networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1408             if (networkResource == null)
1409                 networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate,
1410                         aicMax, aicMin);
1411
1412             networkResource.addNetworkResourceCustomization(networkResourceCustomization);
1413             networkResourceCustomization.setNetworkResource(networkResource);
1414         }
1415
1416         return networkResourceCustomization;
1417     }
1418
1419     protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) {
1420         NetworkResource networkResource = null;
1421         for (NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()) {
1422             if (networkCustom.getNetworkResource() != null
1423                     && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) {
1424                 networkResource = networkCustom.getNetworkResource();
1425             }
1426         }
1427         if (networkResource == null)
1428             networkResource = networkRepo.findResourceByModelUUID(modelUUID);
1429
1430         return networkResource;
1431     }
1432
1433     protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate,
1434             ToscaResourceStructure toscaResourceStructure) {
1435         NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization();
1436         networkResourceCustomization.setModelInstanceName(
1437                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
1438         networkResourceCustomization.setModelCustomizationUUID(
1439                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
1440
1441         networkResourceCustomization.setNetworkTechnology(
1442                 testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1443                         SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)));
1444         networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper()
1445                 .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)));
1446         networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper()
1447                 .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)));
1448         networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper()
1449                 .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)));
1450         return networkResourceCustomization;
1451     }
1452
1453     protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate,
1454             ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) {
1455         NetworkResource networkResource = new NetworkResource();
1456         String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
1457                 networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
1458
1459         if ("true".equalsIgnoreCase(providerNetwork)) {
1460             networkResource.setNeutronNetworkType(PROVIDER);
1461         } else {
1462             networkResource.setNeutronNetworkType(BASIC);
1463         }
1464
1465         networkResource.setModelName(
1466                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
1467
1468         networkResource.setModelInvariantUUID(
1469                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
1470         networkResource.setModelUUID(
1471                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
1472         networkResource.setModelVersion(
1473                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
1474
1475         networkResource.setAicVersionMax(aicMax);
1476         networkResource.setAicVersionMin(aicMin);
1477         networkResource.setToscaNodeType(networkNodeTemplate.getType());
1478         networkResource.setDescription(
1479                 testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
1480         networkResource.setOrchestrationMode(HEAT);
1481         networkResource.setHeatTemplate(heatTemplate);
1482         return networkResource;
1483     }
1484
1485     protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate,
1486             ToscaResourceStructure toscaResourceStructure, Service service) {
1487
1488         CollectionNetworkResourceCustomization collectionNetworkResourceCustomization =
1489                 new CollectionNetworkResourceCustomization();
1490
1491         // **** Build Object to populate Collection_Resource table
1492         CollectionResource collectionResource = new CollectionResource();
1493
1494         collectionResource
1495                 .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1496         collectionResource.setModelInvariantUUID(
1497                 networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1498         collectionResource
1499                 .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1500         collectionResource
1501                 .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1502         collectionResource
1503                 .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1504         collectionResource.setToscaNodeType(networkNodeTemplate.getType());
1505
1506         toscaResourceStructure.setCatalogCollectionResource(collectionResource);
1507
1508         // **** Build object to populate Collection_Resource_Customization table
1509         NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization();
1510
1511         ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1512                 "cr_function"));
1513         ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1514                 "cr_role"));
1515         ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1516                 "cr_type"));
1517
1518         ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1519         ncfc.setModelCustomizationUUID(
1520                 networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1521
1522         Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>();
1523         networkResourceCustomizationSet.add(collectionNetworkResourceCustomization);
1524
1525         ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet);
1526
1527         ncfc.setCollectionResource(collectionResource);
1528         toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc);
1529
1530         // *** Build object to populate the Instance_Group table
1531         List<Group> groupList =
1532                 toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
1533                         networkNodeTemplate, "org.openecomp.groups.NetworkCollection");
1534
1535         List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>();
1536
1537         List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList =
1538                 new ArrayList<CollectionResourceInstanceGroupCustomization>();
1539
1540         for (Group group : groupList) {
1541
1542             NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup();
1543             Metadata instanceMetadata = group.getMetadata();
1544             networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1545             networkInstanceGroup
1546                     .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1547             networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1548             networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1549             networkInstanceGroup.setToscaNodeType(group.getType());
1550             networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set
1551             // Role
1552             networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set
1553             // type
1554             networkInstanceGroup.setCollectionResource(collectionResource);
1555
1556             // ****Build object to populate
1557             // Collection_Resource_Instance_Group_Customization table
1558             CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization =
1559                     new CollectionResourceInstanceGroupCustomization();
1560             crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup);
1561             crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1562             crInstanceGroupCustomization.setModelCustomizationUUID(
1563                     networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1564
1565             // Loop through the template policy to find the subinterface_network_quantity property name. Then extract
1566             // the value for it.
1567             List<Policy> policyList =
1568                     toscaResourceStructure.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(
1569                             networkNodeTemplate, "org.openecomp.policies.scaling.Fixed");
1570
1571             if (policyList != null) {
1572                 for (Policy policy : policyList) {
1573                     for (String policyNetworkCollection : policy.getTargets()) {
1574
1575                         if (policyNetworkCollection.equalsIgnoreCase(group.getName())) {
1576
1577                             Map<String, Object> propMap = policy.getPolicyProperties();
1578
1579                             if (propMap.get("quantity") != null) {
1580
1581                                 String quantity = toscaResourceStructure.getSdcCsarHelper()
1582                                         .getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1583                                                 getPropertyInput(propMap.get("quantity").toString()));
1584
1585                                 if (quantity != null) {
1586                                     crInstanceGroupCustomization
1587                                             .setSubInterfaceNetworkQuantity(Integer.parseInt(quantity));
1588                                 }
1589
1590                             }
1591
1592                         }
1593                     }
1594                 }
1595             }
1596
1597             crInstanceGroupCustomization.setDescription(
1598                     toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1599                             instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
1600                                     + "_network_collection_description"));
1601             crInstanceGroupCustomization.setFunction(
1602                     toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate,
1603                             instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
1604                                     + "_network_collection_function"));
1605             crInstanceGroupCustomization.setCollectionResourceCust(ncfc);
1606             collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization);
1607
1608             networkInstanceGroup
1609                     .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList);
1610
1611             networkInstanceGroupList.add(networkInstanceGroup);
1612
1613
1614             toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList);
1615
1616             List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper()
1617                     .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL);
1618
1619             List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>();
1620
1621             // *****Build object to populate the NetworkResource table
1622             NetworkResource networkResource = new NetworkResource();
1623
1624             for (NodeTemplate vlNodeTemplate : vlNodeList) {
1625
1626                 String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(
1627                         vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
1628
1629                 if ("true".equalsIgnoreCase(providerNetwork)) {
1630                     networkResource.setNeutronNetworkType(PROVIDER);
1631                 } else {
1632                     networkResource.setNeutronNetworkType(BASIC);
1633                 }
1634
1635                 networkResource
1636                         .setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1637
1638                 networkResource.setModelInvariantUUID(
1639                         vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1640                 networkResource
1641                         .setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1642                 networkResource
1643                         .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1644
1645                 networkResource.setAicVersionMax(
1646                         vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
1647
1648                 TempNetworkHeatTemplateLookup tempNetworkLookUp =
1649                         tempNetworkLookupRepo.findFirstBynetworkResourceModelName(
1650                                 vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1651
1652                 if (tempNetworkLookUp != null) {
1653
1654                     HeatTemplate heatTemplate =
1655                             heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
1656                     networkResource.setHeatTemplate(heatTemplate);
1657
1658                     networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin());
1659
1660                 }
1661
1662                 networkResource.setToscaNodeType(vlNodeTemplate.getType());
1663                 networkResource.setDescription(
1664                         vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1665                 networkResource.setOrchestrationMode(HEAT);
1666
1667                 // Build object to populate the
1668                 // Collection_Network_Resource_Customization table
1669                 for (NodeTemplate memberNode : group.getMemberNodes()) {
1670                     collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName());
1671                 }
1672
1673                 collectionNetworkResourceCustomization.setModelCustomizationUUID(
1674                         vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1675
1676                 collectionNetworkResourceCustomization.setNetworkTechnology(
1677                         toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate,
1678                                 SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
1679                 collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper()
1680                         .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
1681                 collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper()
1682                         .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
1683                 collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper()
1684                         .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
1685                 collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup);
1686                 collectionNetworkResourceCustomization.setNetworkResource(networkResource);
1687                 collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc);
1688
1689                 collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization);
1690             }
1691
1692         }
1693
1694         return collectionNetworkResourceCustomization;
1695     }
1696
1697     protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group,
1698             VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) {
1699
1700         Metadata instanceMetadata = group.getMetadata();
1701         // Populate InstanceGroup
1702         VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup();
1703
1704         vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1705         vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1706         vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1707         vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1708         vfcInstanceGroup.setToscaNodeType(group.getType());
1709         vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
1710         vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
1711
1712         // Populate VNFCInstanceGroupCustomization
1713         VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization();
1714
1715         vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization);
1716         vnfResourceCustomization.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
1717
1718         vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
1719         vfcInstanceGroup.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
1720
1721         vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1722
1723         String getInputName = null;
1724         String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
1725                 "vfc_instance_group_function");
1726         if (groupProperty != null) {
1727             int getInputIndex = groupProperty.indexOf("{get_input=");
1728             if (getInputIndex > -1) {
1729                 getInputName = groupProperty.substring(getInputIndex + 11, groupProperty.length() - 1);
1730             }
1731         }
1732         vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper()
1733                 .getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName));
1734         vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
1735
1736
1737         return vfcInstanceGroupCustom;
1738
1739     }
1740
1741     protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate,
1742             ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure,
1743             IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service,
1744             Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet) {
1745
1746         VfModuleCustomization vfModuleCustomization =
1747                 findExistingVfModuleCustomization(vnfResource, vfModuleData.getVfModuleModelCustomizationUUID());
1748         if (vfModuleCustomization == null) {
1749             VfModule vfModule = findExistingVfModule(vnfResource,
1750                     vfTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
1751             Metadata vfMetadata = group.getMetadata();
1752             if (vfModule == null)
1753                 vfModule = createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata);
1754
1755             vfModuleCustomization = createVfModuleCustomization(group, toscaResourceStructure, vfModule, vfModuleData);
1756             vfModuleCustomization.setVnfCustomization(vnfResource);
1757             setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization,
1758                     vfMetadata);
1759             vfModuleCustomization.setVfModule(vfModule);
1760             vfModule.getVfModuleCustomization().add(vfModuleCustomization);
1761             vnfResource.getVfModuleCustomizations().add(vfModuleCustomization);
1762         } else {
1763             vfResourceStructure.setAlreadyDeployed(true);
1764         }
1765
1766         // ******************************************************************************************************************
1767         // * Extract VFC's and CVFC's then add them to VFModule
1768         // ******************************************************************************************************************
1769
1770         Set<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations =
1771                 new HashSet<CvnfcConfigurationCustomization>();
1772         Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>();
1773         Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>();
1774
1775         // Only set the CVNFC if this vfModule group is a member of it.
1776         List<NodeTemplate> groupMembers =
1777                 toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfTemplate, group);
1778         String vfModuleMemberName = null;
1779
1780         for (NodeTemplate node : groupMembers) {
1781             vfModuleMemberName = node.getName();
1782         }
1783
1784         // Extract CVFC lists
1785         List<NodeTemplate> cvfcList =
1786                 toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate, SdcTypes.CVFC);
1787
1788         for (NodeTemplate cvfcTemplate : cvfcList) {
1789             boolean cvnfcVfModuleNameMatch = false;
1790
1791             for (NodeTemplate node : groupMembers) {
1792                 vfModuleMemberName = node.getName();
1793
1794                 if (vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())) {
1795                     cvnfcVfModuleNameMatch = true;
1796                     break;
1797                 }
1798             }
1799
1800             if (vfModuleMemberName != null && cvnfcVfModuleNameMatch) {
1801
1802                 // Extract associated VFC - Should always be just one
1803                 List<NodeTemplate> vfcList =
1804                         toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC);
1805
1806                 for (NodeTemplate vfcTemplate : vfcList) {
1807
1808                     VnfcCustomization vnfcCustomization = new VnfcCustomization();
1809                     VnfcCustomization existingVnfcCustomization = null;
1810
1811                     existingVnfcCustomization = findExistingVfc(existingVnfcSet,
1812                             vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1813
1814                     if (existingVnfcCustomization == null) {
1815                         vnfcCustomization = new VnfcCustomization();
1816                     } else {
1817                         vnfcCustomization = existingVnfcCustomization;
1818                     }
1819
1820                     // Only Add Abstract VNFC's to our DB, ignore all others
1821                     if (existingVnfcCustomization == null && vfcTemplate.getMetaData()
1822                             .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) {
1823                         vnfcCustomization.setModelCustomizationUUID(
1824                                 vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1825                         vnfcCustomization.setModelInstanceName(vfcTemplate.getName());
1826                         vnfcCustomization.setModelInvariantUUID(
1827                                 vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1828                         vnfcCustomization
1829                                 .setModelName(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1830                         vnfcCustomization
1831                                 .setModelUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1832
1833                         vnfcCustomization.setModelVersion(
1834                                 testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
1835                         vnfcCustomization.setDescription(testNull(
1836                                 vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
1837                         vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType()));
1838
1839                         vnfcCustomizations.add(vnfcCustomization);
1840                         existingVnfcSet.add(vnfcCustomization);
1841                     }
1842
1843                     // This check is needed incase the VFC subcategory is
1844                     // something other than Abstract. In that case we want to
1845                     // skip adding that record to our DB.
1846                     if (vnfcCustomization.getModelCustomizationUUID() != null) {
1847                         CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
1848                         cvnfcCustomization.setModelCustomizationUUID(
1849                                 cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1850                         cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName());
1851                         cvnfcCustomization.setModelInvariantUUID(
1852                                 cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1853                         cvnfcCustomization
1854                                 .setModelName(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1855                         cvnfcCustomization
1856                                 .setModelUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1857
1858                         cvnfcCustomization.setModelVersion(
1859                                 testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
1860                         cvnfcCustomization.setDescription(testNull(
1861                                 cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
1862                         cvnfcCustomization.setToscaNodeType(testNull(cvfcTemplate.getType()));
1863
1864                         if (existingVnfcCustomization != null) {
1865                             cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization);
1866                         } else {
1867                             cvnfcCustomization.setVnfcCustomization(vnfcCustomization);
1868                         }
1869
1870                         cvnfcCustomization.setNfcFunction(toscaResourceStructure.getSdcCsarHelper()
1871                                 .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_function"));
1872                         cvnfcCustomization.setNfcNamingCode(toscaResourceStructure.getSdcCsarHelper()
1873                                 .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_naming_code"));
1874                         cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
1875
1876                         cvnfcCustomizations.add(cvnfcCustomization);
1877                         existingCvnfcSet.add(cvnfcCustomization);
1878
1879                         // *****************************************************************************************************************************************
1880                         // * Extract Fabric Configuration
1881                         // *****************************************************************************************************************************************
1882
1883                         List<NodeTemplate> fabricConfigList = toscaResourceStructure.getSdcCsarHelper()
1884                                 .getNodeTemplateBySdcType(vfTemplate, SdcTypes.CONFIGURATION);
1885
1886                         for (NodeTemplate fabricTemplate : fabricConfigList) {
1887
1888                             ConfigurationResource fabricConfig = null;
1889
1890                             ConfigurationResource existingConfig = findExistingConfiguration(service,
1891                                     fabricTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1892
1893                             if (existingConfig == null) {
1894
1895                                 fabricConfig = createFabricConfiguration(fabricTemplate, toscaResourceStructure);
1896
1897                             } else {
1898                                 fabricConfig = existingConfig;
1899                             }
1900
1901                             CvnfcConfigurationCustomization cvnfcConfigurationCustomization =
1902                                     createCvnfcConfigurationCustomization(fabricTemplate, toscaResourceStructure,
1903                                             vnfResource, vfModuleCustomization, cvnfcCustomization, fabricConfig,
1904                                             vfTemplate, vfModuleMemberName);
1905                             cvnfcConfigurationCustomizations.add(cvnfcConfigurationCustomization);
1906
1907                             fabricConfig.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
1908                         }
1909                         cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
1910                     }
1911
1912                 }
1913
1914             }
1915         }
1916         vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations);
1917
1918         return vfModuleCustomization;
1919     }
1920
1921     protected CvnfcConfigurationCustomization createCvnfcConfigurationCustomization(NodeTemplate fabricTemplate,
1922             ToscaResourceStructure toscaResourceStruct, VnfResourceCustomization vnfResource,
1923             VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization,
1924             ConfigurationResource configResource, NodeTemplate vfTemplate, String vfModuleMemberName) {
1925
1926         Metadata fabricMetadata = fabricTemplate.getMetaData();
1927
1928         CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
1929
1930         cvnfcConfigurationCustomization.setConfigurationResource(configResource);
1931
1932         cvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
1933
1934         cvnfcConfigurationCustomization
1935                 .setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1936         cvnfcConfigurationCustomization.setModelInstanceName(fabricTemplate.getName());
1937
1938         List<Policy> policyList = toscaResourceStruct.getSdcCsarHelper()
1939                 .getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(vfTemplate, "org.openecomp.policies.External");
1940
1941         if (policyList != null) {
1942             for (Policy policy : policyList) {
1943
1944                 for (String policyCvfcTarget : policy.getTargets()) {
1945
1946                     if (policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)) {
1947
1948                         Map<String, Object> propMap = policy.getPolicyProperties();
1949
1950                         if (propMap.get("type").toString().equalsIgnoreCase("Fabric Policy")) {
1951                             cvnfcConfigurationCustomization.setPolicyName(propMap.get("name").toString());
1952                         }
1953                     }
1954                 }
1955             }
1956         }
1957
1958         cvnfcConfigurationCustomization.setConfigurationFunction(
1959                 toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "function"));
1960         cvnfcConfigurationCustomization.setConfigurationRole(
1961                 toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "role"));
1962         cvnfcConfigurationCustomization.setConfigurationType(
1963                 toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "type"));
1964
1965         return cvnfcConfigurationCustomization;
1966     }
1967
1968     protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID) {
1969         ConfigurationResource configResource = null;
1970         for (ConfigurationResourceCustomization configurationResourceCustom : service
1971                 .getConfigurationCustomizations()) {
1972             if (configurationResourceCustom.getConfigurationResource() != null
1973                     && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
1974                 configResource = configurationResourceCustom.getConfigurationResource();
1975             }
1976         }
1977
1978         return configResource;
1979     }
1980
1981     protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource,
1982             String vfModuleModelCustomizationUUID) {
1983         VfModuleCustomization vfModuleCustomization = null;
1984         for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
1985             if (vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)) {
1986                 vfModuleCustomization = vfModuleCustom;
1987             }
1988         }
1989         return vfModuleCustomization;
1990     }
1991
1992     protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) {
1993         VfModule vfModule = null;
1994         for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
1995             if (vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)) {
1996                 vfModule = vfModuleCustom.getVfModule();
1997             }
1998         }
1999         if (vfModule == null)
2000             vfModule = vfModuleRepo.findByModelUUID(modelUUID);
2001
2002         return vfModule;
2003     }
2004
2005     protected VfModuleCustomization createVfModuleCustomization(Group group,
2006             ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) {
2007         VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
2008
2009         vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID());
2010
2011         vfModuleCustomization.setVfModule(vfModule);
2012
2013         String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2014                 SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT);
2015         if (initialCount != null && initialCount.length() > 0) {
2016             vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount));
2017         }
2018
2019         vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper()
2020                 .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT)));
2021
2022         String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2023                 SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT);
2024         if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) {
2025             vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount));
2026         }
2027
2028         vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2029                 SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL));
2030
2031         String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2032                 SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES);
2033         if (maxInstances != null && maxInstances.length() > 0) {
2034             vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances));
2035         }
2036
2037         String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2038                 SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES);
2039         if (minInstances != null && minInstances.length() > 0) {
2040             vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances));
2041         }
2042         return vfModuleCustomization;
2043     }
2044
2045     protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure,
2046             IVfModuleData vfModuleData, Metadata vfMetadata) {
2047         VfModule vfModule = new VfModule();
2048         String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID();
2049
2050         if (vfModuleModelUUID == null) {
2051             vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
2052                     SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
2053         } else if (vfModuleModelUUID.indexOf('.') > -1) {
2054             vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.'));
2055         }
2056
2057         vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper()
2058                 .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
2059         vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
2060                 SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
2061         vfModule.setModelUUID(vfModuleModelUUID);
2062         vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
2063                 SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
2064         vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
2065                 SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2066
2067         String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
2068                 SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE);
2069         if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) {
2070             vfModule.setIsBase(true);
2071         } else {
2072             vfModule.setIsBase(false);
2073         }
2074         return vfModule;
2075     }
2076
2077     protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure,
2078             VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization,
2079             Metadata vfMetadata) {
2080
2081         Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream()
2082                 .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID()
2083                         .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata,
2084                                 SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)))
2085                 .findFirst();
2086
2087         if (matchingObject.isPresent()) {
2088             List<HeatFiles> heatFilesList = new ArrayList<>();
2089             List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>();
2090             List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>();
2091             HeatTemplate parentHeatTemplate = new HeatTemplate();
2092             String parentArtifactType = null;
2093             Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts());
2094             for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
2095
2096                 List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>();
2097
2098                 if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) {
2099                     checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact,
2100                             childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure);
2101                 }
2102
2103                 if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
2104                     parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact);
2105
2106                     if (!childNestedHeatTemplates.isEmpty()) {
2107
2108                         if (parentArtifactType != null
2109                                 && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) {
2110                             volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0));
2111                         } else {
2112                             heatChildTemplates.add(childNestedHeatTemplates.get(0));
2113                         }
2114                     }
2115                 }
2116
2117             }
2118             if (!heatFilesList.isEmpty()) {
2119                 vfModule.setHeatFiles(heatFilesList);
2120             }
2121
2122
2123             // Set all Child Templates related to HEAT_VOLUME
2124             if (!volumeHeatChildTemplates.isEmpty()) {
2125                 if (vfModule.getVolumeHeatTemplate() != null) {
2126                     vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates);
2127                 } else {
2128                     logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()");
2129                 }
2130             }
2131
2132             // Set all Child Templates related to HEAT
2133             if (!heatChildTemplates.isEmpty()) {
2134                 if (vfModule.getModuleHeatTemplate() != null) {
2135                     vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates);
2136                 } else {
2137                     logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()");
2138                 }
2139             }
2140         }
2141     }
2142
2143     protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization,
2144             List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates,
2145             HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) {
2146         if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) {
2147             vfModuleArtifact.incrementDeployedInDB();
2148             vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate());
2149         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) {
2150             vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate());
2151             VfModuleArtifact volVfModuleArtifact =
2152                     this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
2153             vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment());
2154             vfModuleArtifact.incrementDeployedInDB();
2155         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
2156             if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) {
2157                 vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment());
2158             } else {
2159                 vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment());
2160             }
2161             vfModuleArtifact.incrementDeployedInDB();
2162         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) {
2163             heatFilesList.add(vfModuleArtifact.getHeatFiles());
2164             vfModuleArtifact.incrementDeployedInDB();
2165         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
2166             nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate());
2167             vfModuleArtifact.incrementDeployedInDB();
2168         }
2169     }
2170
2171     protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate,
2172             ToscaResourceStructure toscaResourceStructure, Service service) {
2173         VnfResourceCustomization vnfResourceCustomization = null;
2174         if (vnfResourceCustomization == null) {
2175             VnfResource vnfResource = findExistingVnfResource(service,
2176                     vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2177
2178             if (vnfResource == null)
2179                 vnfResource = createVnfResource(vfNodeTemplate);
2180
2181             vnfResourceCustomization =
2182                     createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure, vnfResource);
2183             vnfResourceCustomization.setVnfResources(vnfResource);
2184             vnfResourceCustomization.setService(service);
2185             vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization);
2186
2187         }
2188         return vnfResourceCustomization;
2189     }
2190
2191     protected VnfResource findExistingVnfResource(Service service, String modelUUID) {
2192         VnfResource vnfResource = null;
2193         for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
2194             if (vnfResourceCustom.getVnfResources() != null
2195                     && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) {
2196                 vnfResource = vnfResourceCustom.getVnfResources();
2197             }
2198         }
2199         if (vnfResource == null)
2200             vnfResource = vnfRepo.findResourceByModelUUID(modelUUID);
2201
2202         return vnfResource;
2203     }
2204
2205     protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate,
2206             ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) {
2207         VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
2208         vnfResourceCustomization.setModelCustomizationUUID(
2209                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
2210         vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName());
2211
2212         vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
2213                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
2214         vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
2215                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code")));
2216         vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
2217                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
2218         vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
2219                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
2220
2221         vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper()
2222                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN));
2223
2224         vnfResourceCustomization.setBlueprintName(testNull(toscaResourceStructure.getSdcCsarHelper()
2225                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_NAME)));
2226
2227         vnfResourceCustomization.setBlueprintVersion(testNull(toscaResourceStructure.getSdcCsarHelper()
2228                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_VERSION)));
2229
2230         String skipPostInstConfText = toscaResourceStructure.getSdcCsarHelper()
2231                 .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SKIP_POST_INST_CONF);
2232         if (skipPostInstConfText != null) {
2233             vnfResourceCustomization.setSkipPostInstConf(Boolean.parseBoolean(skipPostInstConfText));
2234         }
2235
2236         vnfResourceCustomization.setVnfResources(vnfResource);
2237         vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(
2238                 vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)));
2239
2240         CapabilityAssignments vnfCustomizationCapability =
2241                 toscaResourceStructure.getSdcCsarHelper().getCapabilitiesOf(vfNodeTemplate);
2242
2243         if (vnfCustomizationCapability != null) {
2244             CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE);
2245
2246             if (capAssign != null) {
2247                 vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
2248                         .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2249                 vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper()
2250                         .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2251             }
2252
2253         }
2254
2255         toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization);
2256
2257         return vnfResourceCustomization;
2258     }
2259
2260     protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) {
2261         VnfResource vnfResource = new VnfResource();
2262         vnfResource.setModelInvariantUUID(
2263                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
2264         vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
2265         vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
2266
2267         vnfResource.setModelVersion(
2268                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2269         vnfResource.setDescription(
2270                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2271         vnfResource.setOrchestrationMode(HEAT);
2272         vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType()));
2273         vnfResource.setAicVersionMax(
2274                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2275         vnfResource.setAicVersionMin(
2276                 testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2277         vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
2278         vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
2279
2280         return vnfResource;
2281     }
2282
2283     protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate,
2284             ToscaResourceStructure toscaResourceStructure, Service service) {
2285         AllottedResourceCustomization allottedResourceCustomization =
2286                 allottedCustomizationRepo.findOneByModelCustomizationUUID(
2287                         nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2288
2289         if (allottedResourceCustomization == null) {
2290             AllottedResource allottedResource = findExistingAllottedResource(service,
2291                     nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2292
2293             if (allottedResource == null)
2294                 allottedResource = createAR(nodeTemplate);
2295
2296             toscaResourceStructure.setAllottedResource(allottedResource);
2297             allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure);
2298             allottedResourceCustomization.setAllottedResource(allottedResource);
2299             allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization);
2300         }
2301         return allottedResourceCustomization;
2302     }
2303
2304     protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) {
2305         AllottedResource allottedResource = null;
2306         for (AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()) {
2307             if (allottedResourceCustom.getAllottedResource() != null
2308                     && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) {
2309                 allottedResource = allottedResourceCustom.getAllottedResource();
2310             }
2311         }
2312         if (allottedResource == null)
2313             allottedResource = allottedRepo.findResourceByModelUUID(modelUUID);
2314
2315         return allottedResource;
2316     }
2317
2318     protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate,
2319             ToscaResourceStructure toscaResourceStructure) {
2320         AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization();
2321         allottedResourceCustomization.setModelCustomizationUUID(
2322                 testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
2323         allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName());
2324
2325
2326         allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper()
2327                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)));
2328         allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper()
2329                 .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code")));
2330         allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper()
2331                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)));
2332         allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper()
2333                 .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)));
2334
2335         List<NodeTemplate> vfcNodes = toscaResourceStructure.getSdcCsarHelper()
2336                 .getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID());
2337
2338         if (vfcNodes != null) {
2339             for (NodeTemplate vfcNode : vfcNodes) {
2340
2341                 allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper()
2342                         .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid"));
2343                 allottedResourceCustomization
2344                         .setProvidingServiceModelInvariantUUID(toscaResourceStructure.getSdcCsarHelper()
2345                                 .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid"));
2346                 allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper()
2347                         .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name"));
2348             }
2349         }
2350
2351
2352         CapabilityAssignments arCustomizationCapability =
2353                 toscaResourceStructure.getSdcCsarHelper().getCapabilitiesOf(nodeTemplate);
2354
2355         if (arCustomizationCapability != null) {
2356             CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE);
2357
2358             if (capAssign != null) {
2359                 allottedResourceCustomization.setMinInstances(
2360                         Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
2361                                 capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2362                 allottedResourceCustomization.setMaxInstances(
2363                         Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue(
2364                                 capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2365             }
2366         }
2367         return allottedResourceCustomization;
2368     }
2369
2370     protected AllottedResource createAR(NodeTemplate nodeTemplate) {
2371         AllottedResource allottedResource = new AllottedResource();
2372         allottedResource
2373                 .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
2374         allottedResource.setModelInvariantUUID(
2375                 testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
2376         allottedResource
2377                 .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
2378         allottedResource
2379                 .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2380         allottedResource.setToscaNodeType(testNull(nodeTemplate.getType()));
2381         allottedResource.setSubcategory(
2382                 testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
2383         allottedResource
2384                 .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
2385         return allottedResource;
2386     }
2387
2388     protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) {
2389         // Scan the payload downloadResult and extract the HeatTemplate
2390         // parameters
2391         YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes());
2392         return yamlEditor.getParameterList(artifactUUID);
2393     }
2394
2395     protected String testNull(Object object) {
2396
2397         if (object == null) {
2398             return null;
2399         } else if (object.equals("NULL")) {
2400             return null;
2401         } else if (object instanceof Integer) {
2402             return object.toString();
2403         } else if (object instanceof String) {
2404             return (String) object;
2405         } else {
2406             return "Type not recognized";
2407         }
2408     }
2409
2410     protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,
2411             VfModuleArtifact heatNestedArtifact) {
2412
2413         if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure
2414                 .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) {
2415             for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0)
2416                     .getArtifactInfo().getRelatedArtifacts()) {
2417                 if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
2418                     return ASDCConfiguration.HEAT;
2419                 }
2420
2421             }
2422         }
2423
2424         if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null
2425                 && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo()
2426                         .getRelatedArtifacts() != null) {
2427             for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL)
2428                     .get(0).getArtifactInfo().getRelatedArtifacts()) {
2429                 if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
2430                     return ASDCConfiguration.HEAT_VOL;
2431                 }
2432
2433             }
2434         }
2435
2436         // Does not belong to anything
2437         return null;
2438
2439     }
2440
2441     protected static String createVNFName(VfResourceStructure vfResourceStructure) {
2442
2443         return vfResourceStructure.getNotification().getServiceName() + "/"
2444                 + vfResourceStructure.getResourceInstance().getResourceInstanceName();
2445     }
2446
2447     protected static String createVfModuleName(VfModuleStructure vfModuleStructure) {
2448
2449         return createVNFName(vfModuleStructure.getParentVfResource()) + "::"
2450                 + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName();
2451     }
2452
2453     protected String getPropertyInput(String propertyName) {
2454
2455         String inputName = new String();
2456
2457         if (propertyName != null) {
2458             int getInputIndex = propertyName.indexOf("{get_input=");
2459             if (getInputIndex > -1) {
2460                 inputName = propertyName.substring(getInputIndex + 11, propertyName.length() - 1);
2461             }
2462         }
2463
2464         return inputName;
2465     }
2466
2467
2468     protected static Timestamp getCurrentTimeStamp() {
2469
2470         return new Timestamp(new Date().getTime());
2471     }
2472
2473 }
2474