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