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