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