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