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