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