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