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