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