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