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