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