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