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