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