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