Removing ETSI Catalog Manager trigger from ONAP SO
[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.logging.filter.base.ErrorCode;
45 import org.onap.sdc.api.notification.IArtifactInfo;
46 import org.onap.sdc.api.notification.IResourceInstance;
47 import org.onap.sdc.api.notification.IStatusData;
48 import org.onap.sdc.tosca.parser.api.IEntityDetails;
49 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
50 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
51 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery.EntityQueryBuilder;
52 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
53 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery.TopologyTemplateQueryBuilder;
54 import org.onap.sdc.tosca.parser.enums.EntityTemplateType;
55 import org.onap.sdc.tosca.parser.enums.SdcTypes;
56 import org.onap.sdc.tosca.parser.impl.SdcPropertyNames;
57 import org.onap.sdc.toscaparser.api.CapabilityAssignment;
58 import org.onap.sdc.toscaparser.api.NodeTemplate;
59 import org.onap.sdc.toscaparser.api.Property;
60 import org.onap.sdc.toscaparser.api.RequirementAssignment;
61 import org.onap.sdc.toscaparser.api.elements.Metadata;
62 import org.onap.sdc.toscaparser.api.functions.GetInput;
63 import org.onap.sdc.toscaparser.api.parameters.Input;
64 import org.onap.sdc.utils.DistributionStatusEnum;
65 import org.onap.so.asdc.client.ASDCConfiguration;
66 import org.onap.so.asdc.client.exceptions.ArtifactInstallerException;
67 import org.onap.so.asdc.installer.ASDCElementInfo;
68 import org.onap.so.asdc.installer.BigDecimalVersion;
69 import org.onap.so.asdc.installer.IVfModuleData;
70 import org.onap.so.asdc.installer.PnfResourceStructure;
71 import org.onap.so.asdc.installer.ResourceStructure;
72 import org.onap.so.asdc.installer.ToscaResourceStructure;
73 import org.onap.so.asdc.installer.VfModuleArtifact;
74 import org.onap.so.asdc.installer.VfModuleStructure;
75 import org.onap.so.asdc.installer.VfResourceStructure;
76 import org.onap.so.asdc.installer.bpmn.WorkflowResource;
77 import org.onap.so.asdc.util.YamlEditor;
78 import org.onap.so.db.catalog.beans.AllottedResource;
79 import org.onap.so.db.catalog.beans.AllottedResourceCustomization;
80 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
81 import org.onap.so.db.catalog.beans.CollectionResource;
82 import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
83 import org.onap.so.db.catalog.beans.ConfigurationResource;
84 import org.onap.so.db.catalog.beans.ConfigurationResourceCustomization;
85 import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization;
86 import org.onap.so.db.catalog.beans.CvnfcCustomization;
87 import org.onap.so.db.catalog.beans.HeatEnvironment;
88 import org.onap.so.db.catalog.beans.HeatFiles;
89 import org.onap.so.db.catalog.beans.HeatTemplate;
90 import org.onap.so.db.catalog.beans.HeatTemplateParam;
91 import org.onap.so.db.catalog.beans.InstanceGroup;
92 import org.onap.so.db.catalog.beans.InstanceGroupType;
93 import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
94 import org.onap.so.db.catalog.beans.NetworkInstanceGroup;
95 import org.onap.so.db.catalog.beans.NetworkResource;
96 import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
97 import org.onap.so.db.catalog.beans.PnfResource;
98 import org.onap.so.db.catalog.beans.PnfResourceCustomization;
99 import org.onap.so.db.catalog.beans.Service;
100 import org.onap.so.db.catalog.beans.ServiceArtifact;
101 import org.onap.so.db.catalog.beans.ServiceInfo;
102 import org.onap.so.db.catalog.beans.ServiceProxyResourceCustomization;
103 import org.onap.so.db.catalog.beans.SubType;
104 import org.onap.so.db.catalog.beans.TempNetworkHeatTemplateLookup;
105 import org.onap.so.db.catalog.beans.ToscaCsar;
106 import org.onap.so.db.catalog.beans.VFCInstanceGroup;
107 import org.onap.so.db.catalog.beans.VfModule;
108 import org.onap.so.db.catalog.beans.VfModuleCustomization;
109 import org.onap.so.db.catalog.beans.VnfResource;
110 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
111 import org.onap.so.db.catalog.beans.VnfcCustomization;
112 import org.onap.so.db.catalog.beans.VnfcInstanceGroupCustomization;
113 import org.onap.so.db.catalog.data.repository.AllottedResourceCustomizationRepository;
114 import org.onap.so.db.catalog.data.repository.AllottedResourceRepository;
115 import org.onap.so.db.catalog.data.repository.CollectionResourceCustomizationRepository;
116 import org.onap.so.db.catalog.data.repository.CollectionResourceRepository;
117 import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository;
118 import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository;
119 import org.onap.so.db.catalog.data.repository.CvnfcCustomizationRepository;
120 import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository;
121 import org.onap.so.db.catalog.data.repository.HeatEnvironmentRepository;
122 import org.onap.so.db.catalog.data.repository.HeatFilesRepository;
123 import org.onap.so.db.catalog.data.repository.HeatTemplateRepository;
124 import org.onap.so.db.catalog.data.repository.InstanceGroupRepository;
125 import org.onap.so.db.catalog.data.repository.NetworkResourceCustomizationRepository;
126 import org.onap.so.db.catalog.data.repository.NetworkResourceRepository;
127 import org.onap.so.db.catalog.data.repository.PnfCustomizationRepository;
128 import org.onap.so.db.catalog.data.repository.PnfResourceRepository;
129 import org.onap.so.db.catalog.data.repository.ServiceProxyResourceCustomizationRepository;
130 import org.onap.so.db.catalog.data.repository.ServiceRepository;
131 import org.onap.so.db.catalog.data.repository.TempNetworkHeatTemplateRepository;
132 import org.onap.so.db.catalog.data.repository.ToscaCsarRepository;
133 import org.onap.so.db.catalog.data.repository.VFModuleCustomizationRepository;
134 import org.onap.so.db.catalog.data.repository.VFModuleRepository;
135 import org.onap.so.db.catalog.data.repository.VnfResourceRepository;
136 import org.onap.so.db.catalog.data.repository.VnfcCustomizationRepository;
137 import org.onap.so.db.catalog.data.repository.VnfcInstanceGroupCustomizationRepository;
138 import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus;
139 import org.onap.so.db.request.beans.WatchdogDistributionStatus;
140 import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup;
141 import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository;
142 import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository;
143 import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository;
144 import org.onap.so.logger.LoggingAnchor;
145 import org.onap.so.logger.MessageEnum;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
148 import org.springframework.beans.factory.annotation.Autowired;
149 import org.springframework.orm.ObjectOptimisticLockingFailureException;
150 import org.springframework.stereotype.Component;
151 import org.springframework.transaction.annotation.Transactional;
152 import org.springframework.util.CollectionUtils;
153 import com.fasterxml.jackson.core.JsonProcessingException;
154 import com.fasterxml.jackson.databind.ObjectMapper;
155
156 @Component
157 public class ToscaResourceInstaller {
158
159     protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry";
160
161     protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor";
162
163     protected static final String ALLOTTED_RESOURCE = "Allotted Resource";
164
165     protected static final String MULTI_STAGE_DESIGN = "multi_stage_design";
166
167     protected static final String SCALABLE = "scalable";
168
169     protected static final String BASIC = "BASIC";
170
171     protected static final String PROVIDER = "PROVIDER";
172
173     protected static final String HEAT = "HEAT";
174
175     protected static final String MANUAL_RECORD = "MANUAL_RECORD";
176
177     protected static final String MSO = "SO";
178
179     protected static final String SDNC_MODEL_NAME = "sdnc_model_name";
180
181     protected static final String SDNC_MODEL_VERSION = "sdnc_model_version";
182
183     private static String CUSTOMIZATION_UUID = "customizationUUID";
184
185     protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration";
186
187     private static final String CONTROLLER_ACTOR = "controller_actor";
188
189     private static final String CDS_MODEL_NAME = "cds_model_name";
190
191     private static final String CDS_MODEL_VERSION = "cds_model_version";
192
193     private static final String DEFAULT_SOFTWARE_VERSION = "default_software_version";
194
195     @Autowired
196     protected ServiceRepository serviceRepo;
197
198     @Autowired
199     protected InstanceGroupRepository instanceGroupRepo;
200
201     @Autowired
202     protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo;
203
204     @Autowired
205     protected CollectionResourceRepository collectionRepo;
206
207     @Autowired
208     protected CollectionResourceCustomizationRepository collectionCustomizationRepo;
209
210     @Autowired
211     protected ConfigurationResourceCustomizationRepository configCustomizationRepo;
212
213     @Autowired
214     protected ConfigurationResourceRepository configRepo;
215
216     @Autowired
217     protected VnfResourceRepository vnfRepo;
218
219     @Autowired
220     protected VFModuleRepository vfModuleRepo;
221
222     @Autowired
223     protected VFModuleCustomizationRepository vfModuleCustomizationRepo;
224
225     @Autowired
226     protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo;
227
228     @Autowired
229     protected VnfcCustomizationRepository vnfcCustomizationRepo;
230
231     @Autowired
232     protected CvnfcCustomizationRepository cvnfcCustomizationRepo;
233
234     @Autowired
235     protected AllottedResourceRepository allottedRepo;
236
237     @Autowired
238     protected AllottedResourceCustomizationRepository allottedCustomizationRepo;
239
240     @Autowired
241     protected NetworkResourceRepository networkRepo;
242
243     @Autowired
244     protected HeatTemplateRepository heatRepo;
245
246     @Autowired
247     protected HeatEnvironmentRepository heatEnvRepo;
248
249     @Autowired
250     protected HeatFilesRepository heatFilesRepo;
251
252     @Autowired
253     protected NetworkResourceCustomizationRepository networkCustomizationRepo;
254
255     @Autowired
256     protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository;
257     @Autowired
258     protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository;
259     @Autowired
260     protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository;
261
262     @Autowired
263     protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo;
264
265     @Autowired
266     protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository;
267
268     @Autowired
269     protected ToscaCsarRepository toscaCsarRepo;
270
271     @Autowired
272     protected PnfResourceRepository pnfResourceRepository;
273
274     @Autowired
275     protected PnfCustomizationRepository pnfCustomizationRepository;
276
277     @Autowired
278     protected WorkflowResource workflowResource;
279
280     protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class);
281
282     public boolean isCsarAlreadyDeployed(ToscaResourceStructure toscaResourceStructure)
283             throws ArtifactInstallerException {
284         boolean deployed = false;
285         if (toscaResourceStructure == null) {
286             return deployed;
287         }
288
289         IArtifactInfo inputToscaCsar = toscaResourceStructure.getToscaArtifact();
290         String checkSum = inputToscaCsar.getArtifactChecksum();
291         String artifactUuid = inputToscaCsar.getArtifactUUID();
292
293         Optional<ToscaCsar> toscaCsarObj = toscaCsarRepo.findById(artifactUuid);
294         if (toscaCsarObj.isPresent()) {
295             ToscaCsar toscaCsar = toscaCsarObj.get();
296             if (!toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
297                 String errorMessage =
298                         String.format("Csar with UUID: %s already exists.Their checksums don't match", artifactUuid);
299                 throw new ArtifactInstallerException(errorMessage);
300             } else if (toscaCsar.getArtifactChecksum().equalsIgnoreCase(checkSum)) {
301                 deployed = true;
302             }
303         }
304         return deployed;
305     }
306
307     public boolean isResourceAlreadyDeployed(ResourceStructure vfResourceStruct, boolean serviceDeployed)
308             throws ArtifactInstallerException {
309         boolean status = false;
310         ResourceStructure vfResourceStructure = vfResourceStruct;
311         try {
312             status = vfResourceStructure.isDeployedSuccessfully();
313         } catch (RuntimeException e) {
314             status = false;
315             logger.debug("Exception :", e);
316         }
317         try {
318             Service existingService =
319                     serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID());
320             if (existingService != null && !serviceDeployed)
321                 status = true;
322             if (status) {
323                 logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
324                         vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
325                         vfResourceStructure.getNotification().getServiceName(),
326                         BigDecimalVersion.castAndCheckNotificationVersionToString(
327                                 vfResourceStructure.getNotification().getServiceVersion()),
328                         vfResourceStructure.getNotification().getServiceUUID(),
329                         vfResourceStructure.getResourceInstance().getResourceName(), "", "");
330                 WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(
331                         vfResourceStruct.getNotification().getDistributionID(), MSO);
332                 wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
333                 watchdogCDStatusRepository.saveAndFlush(wdStatus);
334             } else {
335                 logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(),
336                         vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(),
337                         vfResourceStructure.getNotification().getServiceName(),
338                         BigDecimalVersion.castAndCheckNotificationVersionToString(
339                                 vfResourceStructure.getNotification().getServiceVersion()),
340                         vfResourceStructure.getNotification().getServiceUUID(),
341                         vfResourceStructure.getResourceInstance().getResourceName(), "", "");
342             }
343             return status;
344         } catch (Exception e) {
345             logger.error(LoggingAnchor.THREE, MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(),
346                     ErrorCode.SchemaError.getValue(), "Exception - isResourceAlreadyDeployed");
347             throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e);
348         }
349     }
350
351     public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException {
352         logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}",
353                 iStatus.getDistributionID(), iStatus.getComponentName());
354
355         try {
356             WatchdogComponentDistributionStatus cdStatus =
357                     new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), iStatus.getComponentName());
358             cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString());
359             watchdogCDStatusRepository.save(cdStatus);
360
361         } catch (Exception e) {
362             logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage());
363             throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage());
364         }
365     }
366
367
368     @Transactional(rollbackFor = {ArtifactInstallerException.class})
369     public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct)
370             throws ArtifactInstallerException {
371         if (resourceStruct instanceof VfResourceStructure) {
372             installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct);
373         } else if (resourceStruct instanceof PnfResourceStructure) {
374             installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct);
375         } else {
376             logger.warn("Unrecognized resource type");
377         }
378     }
379
380     private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct)
381             throws ArtifactInstallerException {
382
383         // PCLO: in case of deployment failure, use a string that will represent
384         // the type of artifact that failed...
385         List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
386         try {
387             createToscaCsar(toscaResourceStruct);
388             Service service = createService(toscaResourceStruct, resourceStruct);
389
390             processResourceSequence(toscaResourceStruct, service);
391             processPnfResources(toscaResourceStruct, service, resourceStruct);
392             serviceRepo.save(service);
393
394             WatchdogComponentDistributionStatus status =
395                     new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
396             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name());
397             watchdogCDStatusRepository.save(status);
398
399             toscaResourceStruct.setSuccessfulDeployment();
400
401         } catch (Exception e) {
402             logger.debug("Exception :", e);
403             WatchdogComponentDistributionStatus status =
404                     new WatchdogComponentDistributionStatus(resourceStruct.getNotification().getDistributionID(), MSO);
405             status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name());
406             watchdogCDStatusRepository.save(status);
407             Throwable dbExceptionToCapture = e;
408             while (!(dbExceptionToCapture instanceof ConstraintViolationException
409                     || dbExceptionToCapture instanceof LockAcquisitionException)
410                     && (dbExceptionToCapture.getCause() != null)) {
411                 dbExceptionToCapture = dbExceptionToCapture.getCause();
412             }
413
414             if (dbExceptionToCapture instanceof ConstraintViolationException
415                     || dbExceptionToCapture instanceof LockAcquisitionException) {
416                 logger.warn(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(),
417                         resourceStruct.getResourceInstance().getResourceName(),
418                         resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(),
419                         "Exception - ASCDC Artifact already deployed", e);
420             } else {
421                 String elementToLog = (!artifactListForLogging.isEmpty()
422                         ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString()
423                         : "No element listed");
424                 logger.error(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog,
425                         ErrorCode.DataError.getValue(), "Exception caught during installation of "
426                                 + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback",
427                         e);
428                 throw new ArtifactInstallerException(
429                         "Exception caught during installation of "
430                                 + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.",
431                         e);
432             }
433         }
434     }
435
436     @Transactional(rollbackFor = {ArtifactInstallerException.class})
437     public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct)
438             throws ArtifactInstallerException {
439         VfResourceStructure vfResourceStructure = vfResourceStruct;
440         extractHeatInformation(toscaResourceStruct, vfResourceStructure);
441
442         // PCLO: in case of deployment failure, use a string that will represent
443         // the type of artifact that failed...
444         List<ASDCElementInfo> artifactListForLogging = new ArrayList<>();
445         try {
446             createToscaCsar(toscaResourceStruct);
447             createService(toscaResourceStruct, vfResourceStruct);
448             Service service = toscaResourceStruct.getCatalogService();
449             createServiceInfo(toscaResourceStruct, service);
450
451             List<IEntityDetails> vfEntityList = getEntityDetails(toscaResourceStruct,
452                     EntityQuery.newBuilder(SdcTypes.VF), TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);
453
454             List<IEntityDetails> arEntityDetails = new ArrayList<IEntityDetails>();
455
456             for (IEntityDetails vfEntityDetails : vfEntityList) {
457
458                 Metadata metadata = vfEntityDetails.getMetadata();
459                 String category = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);
460
461                 if (ALLOTTED_RESOURCE.equalsIgnoreCase(category)) {
462                     arEntityDetails.add(vfEntityDetails);
463                 }
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.setDefaultSoftwareVersion(getStringValue(properties.get(DEFAULT_SOFTWARE_VERSION)));
990         pnfResourceCustomization.setPnfResources(pnfResource);
991         return pnfResourceCustomization;
992     }
993
994     /**
995      * Get value from {@link Property} and cast to boolean value. Return true if property is null.
996      */
997     private boolean getBooleanValue(Property property) {
998         if (null == property) {
999             return true;
1000         }
1001         Object value = property.getValue();
1002         return new Boolean(String.valueOf(value));
1003     }
1004
1005     /**
1006      * Get value from {@link Property} and cast to String value. Return empty String if property is null value.
1007      */
1008     private String getStringValue(Property property) {
1009         if (null == property) {
1010             return "";
1011         }
1012         Object value = property.getValue();
1013         return String.valueOf(value);
1014     }
1015
1016     protected void processVfModules(IEntityDetails vfEntityDetails, ToscaResourceStructure toscaResourceStruct,
1017             VfResourceStructure vfResourceStructure, Service service, Metadata metadata) throws Exception {
1018
1019         String vfCustomizationCategory =
1020                 vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY);
1021
1022         logger.debug("VF Category is: {} ", vfCustomizationCategory);
1023
1024         String vfCustomizationUUID =
1025                 vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
1026
1027         logger.debug("VFCustomizationUUID= {}", vfCustomizationUUID);
1028
1029         IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance();
1030
1031         // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before
1032         // comparing their VF Modules UUID's
1033         logger.debug(
1034                 "Checking if Notification VF ResourceCustomizationUUID: {} matches Tosca VF Customization UUID: {}",
1035                 vfNotificationResource.getResourceCustomizationUUID(), vfCustomizationUUID);
1036
1037         if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) {
1038
1039             logger.debug("vfCustomizationUUID: {}  matches vfNotificationResource CustomizationUUID ",
1040                     vfCustomizationUUID);
1041
1042             VnfResourceCustomization vnfResource = createVnfResource(vfEntityDetails, toscaResourceStruct, service);
1043
1044             if (vfResourceStructure.getVfModuleStructure() != null
1045                     && !vfResourceStructure.getVfModuleStructure().isEmpty()) {
1046                 Set<CvnfcCustomization> existingCvnfcSet = new HashSet<>();
1047                 Set<VnfcCustomization> existingVnfcSet = new HashSet<>();
1048                 List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom = new ArrayList<>();
1049
1050                 for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) {
1051
1052                     logger.debug("vfModuleStructure: {}", vfModuleStructure);
1053
1054                     List<IEntityDetails> vfModuleEntityList =
1055                             getEntityDetails(toscaResourceStruct,
1056                                     EntityQuery.newBuilder("org.openecomp.groups.VfModule"), TopologyTemplateQuery
1057                                             .newBuilder(SdcTypes.SERVICE).customizationUUID(vfCustomizationUUID),
1058                                     false);
1059
1060                     IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata();
1061
1062                     logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : "
1063                             + vfMetadata.getVfModuleModelCustomizationUUID());
1064
1065                     Optional<IEntityDetails> matchingObject = vfModuleEntityList.stream()
1066                             .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID "
1067                                     + group.getMetadata().getValue("vfModuleModelCustomizationUUID")))
1068                             .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID")
1069                                     .equals(vfMetadata.getVfModuleModelCustomizationUUID()))
1070                             .findFirst();
1071                     if (matchingObject.isPresent()) {
1072                         VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(),
1073                                 toscaResourceStruct, vfResourceStructure, vfMetadata, vnfResource, service,
1074                                 existingCvnfcSet, existingVnfcSet, existingCvnfcConfigurationCustom);
1075                         vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources());
1076                     } else
1077                         throw new Exception(
1078                                 "Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: "
1079                                         + vfMetadata.getVfModuleModelCustomizationUUID());
1080
1081                 }
1082             }
1083
1084             // Check for VNFC Instance Group info and add it if there is
1085             List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStruct,
1086                     EntityQuery.newBuilder("org.openecomp.groups.VfcInstanceGroup"),
1087                     TopologyTemplateQuery.newBuilder(SdcTypes.VF).customizationUUID(vfCustomizationUUID), false);
1088
1089             Set<VnfcCustomization> existingVnfcGroupSet = new HashSet<>();
1090
1091             for (IEntityDetails groupEntity : vfcEntityList) {
1092                 VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = createVNFCInstanceGroup(groupEntity,
1093                         vfEntityDetails, vnfResource, toscaResourceStruct, existingVnfcGroupSet);
1094                 vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
1095             }
1096
1097             List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, vfcEntityList);
1098             if (!CollectionUtils.isEmpty(seqResult)) {
1099                 String resultStr = seqResult.stream().collect(Collectors.joining(","));
1100                 vnfResource.setVnfcInstanceGroupOrder(resultStr);
1101                 logger.debug("vnfcGroupOrder result for service uuid {}: {}", service.getModelUUID(), resultStr);
1102             }
1103             // add this vnfResource with existing vnfResource for this service
1104             addVnfCustomization(service, vnfResource);
1105         } else {
1106             logger.debug("Notification VF ResourceCustomizationUUID: "
1107                     + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match "
1108                     + "Tosca VF Customization UUID: " + vfCustomizationUUID);
1109         }
1110     }
1111
1112     private List<String> processVNFCGroupSequence(ToscaResourceStructure toscaResourceStructure,
1113             List<IEntityDetails> groupEntityDetails) {
1114         if (CollectionUtils.isEmpty(groupEntityDetails)) {
1115             return Collections.emptyList();
1116         }
1117
1118         ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
1119         List<String> strSequence = new ArrayList<>(groupEntityDetails.size());
1120         List<IEntityDetails> tempEntityList = new ArrayList<>(groupEntityDetails.size());
1121         List<IEntityDetails> entities = new ArrayList<>();
1122         tempEntityList.addAll(groupEntityDetails);
1123
1124         for (IEntityDetails vnfcEntityDetails : groupEntityDetails) {
1125
1126             List<IEntityDetails> vnfcMemberNodes = vnfcEntityDetails.getMemberNodes();
1127
1128             boolean hasRequirements = false;
1129             for (IEntityDetails vnfcDetails : vnfcMemberNodes) {
1130
1131                 List<RequirementAssignment> requirements = vnfcDetails.getRequirements();
1132
1133                 if (requirements != null && !requirements.isEmpty()) {
1134                     hasRequirements = true;
1135                     break;
1136                 }
1137             }
1138
1139             if (!hasRequirements) {
1140                 strSequence.add(vnfcEntityDetails.getName());
1141                 tempEntityList.remove(vnfcEntityDetails);
1142                 entities.addAll(vnfcMemberNodes);
1143             }
1144         }
1145
1146         getVNFCGroupSequenceList(strSequence, tempEntityList, entities, iSdcCsarHelper);
1147
1148         return strSequence;
1149
1150     }
1151
1152     private void getVNFCGroupSequenceList(List<String> strSequence, List<IEntityDetails> vnfcGroupDetails,
1153             List<IEntityDetails> vnfcMemberNodes, ISdcCsarHelper iSdcCsarHelper) {
1154         if (CollectionUtils.isEmpty(vnfcGroupDetails)) {
1155             return;
1156         }
1157
1158         List<IEntityDetails> tempGroupList = new ArrayList<>();
1159         tempGroupList.addAll(vnfcGroupDetails);
1160
1161         for (IEntityDetails vnfcGroup : vnfcGroupDetails) {
1162             List<IEntityDetails> members = vnfcGroup.getMemberNodes();
1163             for (IEntityDetails memberNode : members) {
1164                 boolean isAllExists = true;
1165
1166
1167                 List<RequirementAssignment> requirements = memberNode.getRequirements();
1168
1169                 if (requirements == null || requirements.isEmpty()) {
1170                     continue;
1171                 }
1172
1173
1174                 for (RequirementAssignment rqa : requirements) {
1175                     String name = rqa.getNodeTemplateName();
1176                     for (IEntityDetails node : vnfcMemberNodes) {
1177                         if (name.equals(node.getName())) {
1178                             break;
1179                         }
1180                     }
1181
1182                     isAllExists = false;
1183                     break;
1184                 }
1185
1186                 if (isAllExists) {
1187                     strSequence.add(vnfcGroup.getName());
1188                     tempGroupList.remove(vnfcGroupDetails);
1189                     vnfcMemberNodes.addAll(vnfcGroupDetails);
1190                 }
1191             }
1192
1193             if (!tempGroupList.isEmpty() && tempGroupList.size() < vnfcGroupDetails.size()) {
1194                 getVNFCGroupSequenceList(strSequence, tempGroupList, vnfcMemberNodes, iSdcCsarHelper);
1195             }
1196         }
1197     }
1198
1199     public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification,
1200             String consumerId) {
1201         WatchdogServiceModVerIdLookup modVerIdLookup =
1202                 new WatchdogServiceModVerIdLookup(distributionId, servideUUID, distributionNotification, consumerId);
1203         watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup);
1204
1205         try {
1206
1207             WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId);
1208             watchdogDistributionStatusRepository.saveAndFlush(distributionStatus);
1209
1210         } catch (ObjectOptimisticLockingFailureException e) {
1211             logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : {} ", e);
1212             throw e;
1213         }
1214     }
1215
1216     protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct,
1217             VfResourceStructure vfResourceStructure) {
1218         for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1219
1220             switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) {
1221                 case ASDCConfiguration.HEAT:
1222                 case ASDCConfiguration.HEAT_NESTED:
1223                     createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
1224                     break;
1225                 case ASDCConfiguration.HEAT_VOL:
1226                     createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, vfModuleArtifact);
1227                     VfModuleArtifact envModuleArtifact =
1228                             getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
1229                     createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact);
1230                     break;
1231                 case ASDCConfiguration.HEAT_ENV:
1232                     createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact);
1233                     break;
1234                 case ASDCConfiguration.HEAT_ARTIFACT:
1235                     createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, toscaResourceStruct);
1236                     break;
1237                 case ASDCConfiguration.HEAT_NET:
1238                 case ASDCConfiguration.OTHER:
1239                 case ASDCConfiguration.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT:
1240                     logger.warn(LoggingAnchor.FOUR, MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(),
1241                             vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:"
1242                                     + vfModuleArtifact.getArtifactInfo().getArtifactName() + ")",
1243                             ErrorCode.DataError.getValue(), "Artifact type not supported");
1244                     break;
1245                 default:
1246                     break;
1247
1248             }
1249         }
1250     }
1251
1252     protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure,
1253             VfModuleArtifact vfModuleArtifact) {
1254         String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName();
1255         artifactName = artifactName.substring(0, artifactName.indexOf('.'));
1256         for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1257             if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName)
1258                     && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
1259                 return moduleArtifact;
1260             }
1261         }
1262         return null;
1263     }
1264
1265     public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure,
1266             List<String> listTypes) {
1267         String newFileBody = filebody;
1268         for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
1269
1270             if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) {
1271
1272                 newFileBody =
1273                         verifyTheFilePrefixInString(newFileBody, moduleArtifact.getArtifactInfo().getArtifactName());
1274             }
1275         }
1276         return newFileBody;
1277     }
1278
1279     public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) {
1280
1281         String needlePrefix = "file:///";
1282         String prefixedFilenameToVerify = needlePrefix + filenameToVerify;
1283
1284         if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) {
1285             return body;
1286         }
1287
1288         StringBuilder sb = new StringBuilder(body.length());
1289
1290         int currentIndex = 0;
1291         int startIndex = 0;
1292
1293         while (currentIndex != -1) {
1294             startIndex = currentIndex;
1295             currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex);
1296
1297             if (currentIndex == -1) {
1298                 break;
1299             }
1300             // We append from the startIndex up to currentIndex (start of File
1301             // Name)
1302             sb.append(body.substring(startIndex, currentIndex));
1303             sb.append(filenameToVerify);
1304
1305             currentIndex += prefixedFilenameToVerify.length();
1306         }
1307
1308         sb.append(body.substring(startIndex));
1309
1310         return sb.toString();
1311     }
1312
1313     protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure,
1314             ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) {
1315
1316         HeatTemplate existingHeatTemplate =
1317                 heatRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1318
1319         if (existingHeatTemplate == null) {
1320             HeatTemplate heatTemplate = new HeatTemplate();
1321             List<String> typeList = new ArrayList<>();
1322             typeList.add(ASDCConfiguration.HEAT_NESTED);
1323             typeList.add(ASDCConfiguration.HEAT_ARTIFACT);
1324
1325             heatTemplate.setTemplateBody(
1326                     verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
1327             heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1328
1329             if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
1330                 heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
1331             } else {
1332                 heatTemplate.setTimeoutMinutes(240);
1333             }
1334
1335             heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1336             heatTemplate.setVersion(BigDecimalVersion
1337                     .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1338             heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1339
1340             if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1341                 heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1342             } else {
1343                 heatTemplate.setArtifactChecksum(MANUAL_RECORD);
1344             }
1345
1346             Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters(vfModuleArtifact.getResult(),
1347                     vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1348             heatTemplate.setParameters(heatParam);
1349             vfModuleArtifact.setHeatTemplate(heatTemplate);
1350         } else {
1351             if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) {
1352                 existingHeatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout());
1353             }
1354             vfModuleArtifact.setHeatTemplate(existingHeatTemplate);
1355         }
1356     }
1357
1358     protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure,
1359             VfModuleArtifact vfModuleArtifact) {
1360
1361         HeatEnvironment existingHeatEnvironment =
1362                 heatEnvRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1363
1364         if (existingHeatEnvironment == null) {
1365             HeatEnvironment heatEnvironment = new HeatEnvironment();
1366             heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1367             List<String> typeList = new ArrayList<>();
1368             typeList.add(ASDCConfiguration.HEAT);
1369             typeList.add(ASDCConfiguration.HEAT_VOL);
1370             heatEnvironment.setEnvironment(
1371                     verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList));
1372             heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1373             heatEnvironment.setVersion(BigDecimalVersion
1374                     .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1375             heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1376
1377             if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1378                 heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1379             } else {
1380                 heatEnvironment.setArtifactChecksum(MANUAL_RECORD);
1381             }
1382             vfModuleArtifact.setHeatEnvironment(heatEnvironment);
1383         } else {
1384             vfModuleArtifact.setHeatEnvironment(existingHeatEnvironment);
1385         }
1386     }
1387
1388     protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure,
1389             VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) {
1390
1391         HeatFiles existingHeatFiles =
1392                 heatFilesRepo.findByArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1393
1394         if (existingHeatFiles == null) {
1395             HeatFiles heatFile = new HeatFiles();
1396             heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1397             heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription());
1398             heatFile.setFileBody(vfModuleArtifact.getResult());
1399             heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName());
1400             heatFile.setVersion(BigDecimalVersion
1401                     .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion()));
1402             toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID());
1403             if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) {
1404                 heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum());
1405             } else {
1406                 heatFile.setArtifactChecksum(MANUAL_RECORD);
1407             }
1408             vfModuleArtifact.setHeatFiles(heatFile);
1409         } else {
1410             vfModuleArtifact.setHeatFiles(existingHeatFiles);
1411         }
1412     }
1413
1414     protected Service createService(ToscaResourceStructure toscaResourceStructure,
1415             ResourceStructure resourceStructure) {
1416
1417         Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata();
1418         List<Service> services =
1419                 serviceRepo.findByModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1420         Service service;
1421         if (!services.isEmpty() && services.size() > 0) {
1422             service = services.get(0);
1423         } else {
1424             service = new Service();
1425         }
1426
1427         if (serviceMetadata != null) {
1428
1429             if (toscaResourceStructure.getServiceVersion() != null) {
1430                 service.setModelVersion(toscaResourceStructure.getServiceVersion());
1431             }
1432
1433             service.setServiceType(serviceMetadata.getValue("serviceType"));
1434             service.setServiceRole(serviceMetadata.getValue("serviceRole"));
1435             service.setServiceFunction(serviceMetadata.getValue("serviceFunction"));
1436             service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
1437
1438             service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1439             service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1440             service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1441             service.setEnvironmentContext(serviceMetadata.getValue("environmentContext"));
1442
1443             if (resourceStructure != null)
1444                 service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext());
1445
1446             service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1447             service.setCsar(toscaResourceStructure.getCatalogToscaCsar());
1448             service.setNamingPolicy(serviceMetadata.getValue("namingPolicy"));
1449             String generateNaming = serviceMetadata.getValue("ecompGeneratedNaming");
1450             Boolean generateNamingValue = null;
1451             if (generateNaming != null) {
1452                 generateNamingValue = "true".equalsIgnoreCase(generateNaming);
1453             }
1454             service.setOnapGeneratedNaming(generateNamingValue);
1455             service.setBlueprintName(serviceMetadata.getValue(CDS_MODEL_NAME));
1456             service.setBlueprintVersion(serviceMetadata.getValue(CDS_MODEL_VERSION));
1457             service.setSkipPostInstConf(Boolean.valueOf(serviceMetadata.getValue(SKIP_POST_INST_CONF)));
1458             service.setControllerActor(serviceMetadata.getValue(CONTROLLER_ACTOR));
1459         }
1460
1461
1462         toscaResourceStructure.setCatalogService(service);
1463         return service;
1464     }
1465
1466     protected ServiceProxyResourceCustomization createServiceProxy(IEntityDetails spEntity, Service service,
1467             ToscaResourceStructure toscaResourceStructure) {
1468
1469         Metadata spMetadata = spEntity.getMetadata();
1470
1471         ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization();
1472
1473         Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>();
1474
1475         spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1476         spCustomizationResource
1477                 .setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1478         spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1479         spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1480         spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1481
1482         spCustomizationResource
1483                 .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1484         spCustomizationResource.setModelInstanceName(spEntity.getName());
1485         spCustomizationResource.setToscaNodeType(spEntity.getToscaType());
1486
1487         String sourceServiceUUID = spMetadata.getValue("sourceModelUuid");
1488
1489         Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID);
1490
1491         spCustomizationResource.setSourceService(sourceService);
1492         spCustomizationResource.setToscaNodeType(spEntity.getToscaType());
1493         serviceProxyCustomizationSet.add(spCustomizationResource);
1494
1495
1496         toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource);
1497
1498         return spCustomizationResource;
1499     }
1500
1501     protected ConfigurationResourceCustomization createConfiguration(IEntityDetails configEntity,
1502             ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization,
1503             Service service, List<ConfigurationResourceCustomization> configurationResourceList) {
1504
1505         ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization(
1506                 configEntity, toscaResourceStructure, spResourceCustomization, service);
1507
1508         ConfigurationResource configResource = null;
1509
1510         ConfigurationResource existingConfigResource = findExistingConfiguration(service,
1511                 configEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID), configurationResourceList);
1512
1513         if (existingConfigResource == null) {
1514             configResource = getConfigurationResource(configEntity);
1515         } else {
1516             configResource = existingConfigResource;
1517         }
1518
1519         configCustomizationResource.setConfigurationResource(configResource);
1520
1521         return configCustomizationResource;
1522     }
1523
1524     protected ConfigurationResource createFabricConfiguration(IEntityDetails fabricEntity,
1525             ToscaResourceStructure toscaResourceStructure) {
1526
1527         Metadata fabricMetadata = fabricEntity.getMetadata();
1528
1529         ConfigurationResource configResource = new ConfigurationResource();
1530
1531         configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1532         configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1533         configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1534         configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1535         configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1536         configResource.setToscaNodeType(fabricEntity.getToscaType());
1537
1538         return configResource;
1539     }
1540
1541     protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) {
1542         Optional<ToscaCsar> toscaCsarOpt =
1543                 toscaCsarRepo.findById(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
1544         ToscaCsar toscaCsar;
1545         if (!toscaCsarOpt.isPresent()) {
1546             toscaCsar = new ToscaCsar();
1547             toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID());
1548         } else {
1549             toscaCsar = toscaCsarOpt.get();
1550         }
1551         if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) {
1552             toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum());
1553         } else {
1554             toscaCsar.setArtifactChecksum(MANUAL_RECORD);
1555         }
1556         toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName());
1557         toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion());
1558         toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription());
1559         toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL());
1560
1561         toscaResourceStructure.setCatalogToscaCsar(toscaCsar);
1562     }
1563
1564     protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) {
1565         VnfcCustomization vnfcCustomization = null;
1566         for (VnfcCustomization vnfcCustom : vnfcCustomizations) {
1567             if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
1568                 vnfcCustomization = vnfcCustom;
1569             }
1570         }
1571
1572         if (vnfcCustomization == null)
1573             vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
1574
1575         return vnfcCustomization;
1576     }
1577
1578     protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations,
1579             String customizationUUID) {
1580         CvnfcCustomization cvnfcCustomization = null;
1581         for (CvnfcCustomization cvnfcCustom : cvnfcCustomizations) {
1582             if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) {
1583                 cvnfcCustomization = cvnfcCustom;
1584             }
1585         }
1586
1587         if (cvnfcCustomization == null)
1588             cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID);
1589
1590         return cvnfcCustomization;
1591     }
1592
1593     protected NetworkResourceCustomization createNetwork(IEntityDetails networkEntity,
1594             ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,
1595             Service service) {
1596
1597         NetworkResourceCustomization networkResourceCustomization =
1598                 networkCustomizationRepo.findOneByModelCustomizationUUID(
1599                         networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1600
1601         boolean networkUUIDsMatch = true;
1602         // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from
1603         // the distribution.
1604         // If not we'll update the Customization record with latest from the distribution
1605         if (networkResourceCustomization != null) {
1606             String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID();
1607             String latestNetworkModelUUID = networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
1608
1609             if (!existingNetworkModelUUID.equals(latestNetworkModelUUID)) {
1610                 networkUUIDsMatch = false;
1611             }
1612
1613         }
1614
1615         if (networkResourceCustomization != null && !networkUUIDsMatch) {
1616
1617             NetworkResource networkResource =
1618                     createNetworkResource(networkEntity, toscaResourceStructure, heatTemplate, aicMax, aicMin);
1619
1620             networkResourceCustomization.setNetworkResource(networkResource);
1621
1622             networkCustomizationRepo.saveAndFlush(networkResourceCustomization);
1623
1624
1625         } else if (networkResourceCustomization == null) {
1626             networkResourceCustomization = createNetworkResourceCustomization(networkEntity, toscaResourceStructure);
1627
1628             NetworkResource networkResource = findExistingNetworkResource(service,
1629                     networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1630             if (networkResource == null)
1631                 networkResource =
1632                         createNetworkResource(networkEntity, toscaResourceStructure, heatTemplate, aicMax, aicMin);
1633
1634             networkResource.addNetworkResourceCustomization(networkResourceCustomization);
1635             networkResourceCustomization.setNetworkResource(networkResource);
1636         }
1637
1638         return networkResourceCustomization;
1639     }
1640
1641     protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) {
1642         NetworkResource networkResource = null;
1643         for (NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()) {
1644             if (networkCustom.getNetworkResource() != null
1645                     && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) {
1646                 networkResource = networkCustom.getNetworkResource();
1647             }
1648         }
1649         if (networkResource == null)
1650             networkResource = networkRepo.findResourceByModelUUID(modelUUID);
1651
1652         return networkResource;
1653     }
1654
1655     protected NetworkResourceCustomization createNetworkResourceCustomization(IEntityDetails networkEntity,
1656             ToscaResourceStructure toscaResourceStructure) {
1657         NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization();
1658         networkResourceCustomization.setModelInstanceName(
1659                 testNull(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
1660         networkResourceCustomization.setModelCustomizationUUID(
1661                 testNull(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
1662
1663         networkResourceCustomization.setNetworkTechnology(
1664                 getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
1665
1666         networkResourceCustomization
1667                 .setNetworkType(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
1668
1669         networkResourceCustomization
1670                 .setNetworkRole(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
1671
1672         networkResourceCustomization
1673                 .setNetworkScope(getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
1674
1675         return networkResourceCustomization;
1676     }
1677
1678     protected NetworkResource createNetworkResource(IEntityDetails vlEntity,
1679             ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) {
1680         NetworkResource networkResource = new NetworkResource();
1681         String providerNetwork =
1682                 getLeafPropertyValue(vlEntity, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
1683
1684         if ("true".equalsIgnoreCase(providerNetwork)) {
1685             networkResource.setNeutronNetworkType(PROVIDER);
1686         } else {
1687             networkResource.setNeutronNetworkType(BASIC);
1688         }
1689
1690         networkResource.setModelName(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
1691
1692         networkResource.setModelInvariantUUID(
1693                 testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
1694         networkResource.setModelUUID(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
1695         networkResource
1696                 .setModelVersion(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
1697
1698         networkResource.setAicVersionMax(aicMax);
1699         networkResource.setAicVersionMin(aicMin);
1700         networkResource.setToscaNodeType(vlEntity.getToscaType());
1701         networkResource
1702                 .setDescription(testNull(vlEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
1703         networkResource.setOrchestrationMode(HEAT);
1704         networkResource.setHeatTemplate(heatTemplate);
1705         return networkResource;
1706     }
1707
1708     protected CollectionNetworkResourceCustomization createNetworkCollection(IEntityDetails cnrEntity,
1709             ToscaResourceStructure toscaResourceStructure, Service service) {
1710
1711         CollectionNetworkResourceCustomization collectionNetworkResourceCustomization =
1712                 new CollectionNetworkResourceCustomization();
1713
1714         // **** Build Object to populate Collection_Resource table
1715         CollectionResource collectionResource = new CollectionResource();
1716
1717         collectionResource.setModelName(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1718         collectionResource
1719                 .setModelInvariantUUID(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1720         collectionResource.setModelUUID(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1721         collectionResource.setModelVersion(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1722         collectionResource.setDescription(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1723         collectionResource.setToscaNodeType(cnrEntity.getToscaType());
1724
1725         toscaResourceStructure.setCatalogCollectionResource(collectionResource);
1726
1727         // **** Build object to populate Collection_Resource_Customization table
1728         NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization();
1729
1730         ncfc.setFunction(getLeafPropertyValue(cnrEntity, "cr_function"));
1731         ncfc.setRole(getLeafPropertyValue(cnrEntity, "cr_role"));
1732         ncfc.setType(getLeafPropertyValue(cnrEntity, "cr_type"));
1733
1734         ncfc.setModelInstanceName(cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1735         ncfc.setModelCustomizationUUID(
1736                 cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1737
1738         Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>();
1739         networkResourceCustomizationSet.add(collectionNetworkResourceCustomization);
1740
1741         ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet);
1742
1743         ncfc.setCollectionResource(collectionResource);
1744         toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc);
1745
1746         // *** Build object to populate the Instance_Group table
1747         List<IEntityDetails> ncEntityList =
1748                 getEntityDetails(toscaResourceStructure,
1749                         EntityQuery.newBuilder("org.openecomp.groups.NetworkCollection"),
1750                         TopologyTemplateQuery.newBuilder(SdcTypes.CR).customizationUUID(
1751                                 cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
1752                         false);
1753
1754         List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>();
1755
1756         List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList =
1757                 new ArrayList<>();
1758
1759         for (IEntityDetails ncGroupEntity : ncEntityList) {
1760
1761             NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup();
1762             Metadata instanceMetadata = ncGroupEntity.getMetadata();
1763             networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1764             networkInstanceGroup
1765                     .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1766             networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1767             networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1768             networkInstanceGroup.setToscaNodeType(ncGroupEntity.getToscaType());
1769             networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set
1770             // Role
1771             networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set
1772             // type
1773             networkInstanceGroup.setCollectionResource(collectionResource);
1774
1775             // ****Build object to populate
1776             // Collection_Resource_Instance_Group_Customization table
1777             CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization =
1778                     new CollectionResourceInstanceGroupCustomization();
1779             crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup);
1780             crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1781             crInstanceGroupCustomization.setModelCustomizationUUID(
1782                     cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1783
1784             // Loop through the template policy to find the subinterface_network_quantity property name. Then extract
1785             // the value for it.
1786             List<IEntityDetails> policyEntityList = getEntityDetails(toscaResourceStructure,
1787                     EntityQuery.newBuilder("org.openecomp.policies.scaling.Fixed"),
1788                     TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), true);
1789
1790             if (policyEntityList != null) {
1791                 for (IEntityDetails policyEntity : policyEntityList) {
1792                     for (String policyNetworkCollection : policyEntity.getTargets()) {
1793
1794                         if (policyNetworkCollection.equalsIgnoreCase(ncGroupEntity.getName())) {
1795
1796                             Map<String, Property> propMap = policyEntity.getProperties();
1797
1798                             if (propMap.get("quantity") != null) {
1799
1800                                 String quantity = getLeafPropertyValue(cnrEntity,
1801                                         getPropertyInput(propMap.get("quantity").toString()));
1802
1803                                 if (quantity != null) {
1804                                     crInstanceGroupCustomization
1805                                             .setSubInterfaceNetworkQuantity(Integer.parseInt(quantity));
1806                                 }
1807
1808                             }
1809
1810                         }
1811                     }
1812                 }
1813             }
1814
1815             crInstanceGroupCustomization.setDescription(
1816                     getLeafPropertyValue(cnrEntity, instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)
1817                             + "_network_collection_description"));
1818
1819             crInstanceGroupCustomization.setFunction(getLeafPropertyValue(cnrEntity,
1820                     instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + "_network_collection_function"));
1821
1822             crInstanceGroupCustomization.setCollectionResourceCust(ncfc);
1823             collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization);
1824
1825             networkInstanceGroup
1826                     .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList);
1827
1828             networkInstanceGroupList.add(networkInstanceGroup);
1829
1830
1831             toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList);
1832
1833             List<IEntityDetails> networkEntityList =
1834                     getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.VL),
1835                             TopologyTemplateQuery.newBuilder(SdcTypes.CR).customizationUUID(
1836                                     cnrEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
1837                             false);
1838
1839             List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>();
1840
1841             // *****Build object to populate the NetworkResource table
1842             NetworkResource networkResource = new NetworkResource();
1843
1844             for (IEntityDetails networkEntity : networkEntityList) {
1845
1846                 String providerNetwork = getLeafPropertyValue(networkEntity,
1847                         SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK);
1848
1849                 if ("true".equalsIgnoreCase(providerNetwork)) {
1850                     networkResource.setNeutronNetworkType(PROVIDER);
1851                 } else {
1852                     networkResource.setNeutronNetworkType(BASIC);
1853                 }
1854
1855                 networkResource.setModelName(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1856
1857                 networkResource.setModelInvariantUUID(
1858                         networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1859                 networkResource.setModelUUID(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1860                 networkResource
1861                         .setModelVersion(networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1862
1863                 networkResource.setAicVersionMax(
1864                         networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES));
1865
1866                 TempNetworkHeatTemplateLookup tempNetworkLookUp =
1867                         tempNetworkLookupRepo.findFirstBynetworkResourceModelName(
1868                                 networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1869
1870                 if (tempNetworkLookUp != null) {
1871
1872                     HeatTemplate heatTemplate =
1873                             heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid());
1874                     networkResource.setHeatTemplate(heatTemplate);
1875
1876                     networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin());
1877
1878                 }
1879
1880                 networkResource.setToscaNodeType(networkEntity.getToscaType());
1881                 networkResource.setDescription(
1882                         networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1883                 networkResource.setOrchestrationMode(HEAT);
1884
1885                 // Build object to populate the
1886                 // Collection_Network_Resource_Customization table
1887                 for (IEntityDetails networkMemberEntity : ncGroupEntity.getMemberNodes()) {
1888                     collectionNetworkResourceCustomization.setModelInstanceName(networkMemberEntity.getName());
1889                 }
1890
1891                 collectionNetworkResourceCustomization.setModelCustomizationUUID(
1892                         networkEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
1893
1894                 collectionNetworkResourceCustomization.setNetworkTechnology(
1895                         getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY));
1896                 collectionNetworkResourceCustomization.setNetworkType(
1897                         getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE));
1898                 collectionNetworkResourceCustomization.setNetworkRole(
1899                         getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE));
1900                 collectionNetworkResourceCustomization.setNetworkScope(
1901                         getLeafPropertyValue(networkEntity, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE));
1902                 collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup);
1903                 collectionNetworkResourceCustomization.setNetworkResource(networkResource);
1904                 collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc);
1905
1906                 collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization);
1907             }
1908
1909         }
1910
1911         return collectionNetworkResourceCustomization;
1912     }
1913
1914     protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(IEntityDetails vfcInstanceEntity,
1915             IEntityDetails vfEntityDetails, VnfResourceCustomization vnfResourceCustomization,
1916             ToscaResourceStructure toscaResourceStructure, Set<VnfcCustomization> existingVnfcGroupSet) {
1917
1918         Metadata instanceMetadata = vfcInstanceEntity.getMetadata();
1919
1920         InstanceGroup existingInstanceGroup =
1921                 instanceGroupRepo.findByModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1922
1923         VFCInstanceGroup vfcInstanceGroup;
1924
1925         if (existingInstanceGroup == null) {
1926             // Populate InstanceGroup
1927             vfcInstanceGroup = new VFCInstanceGroup();
1928             vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
1929             vfcInstanceGroup
1930                     .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
1931             vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
1932             vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
1933             vfcInstanceGroup.setToscaNodeType(vfcInstanceEntity.getToscaType());
1934             vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
1935             vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
1936         } else {
1937             vfcInstanceGroup = (VFCInstanceGroup) existingInstanceGroup;
1938         }
1939
1940         // Populate VNFCInstanceGroupCustomization
1941         VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization();
1942
1943         vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization);
1944         vnfResourceCustomization.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
1945
1946         vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
1947         vfcInstanceGroup.getVnfcInstanceGroupCustomizations().add(vfcInstanceGroupCustom);
1948
1949         vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
1950
1951         String getInputName = null;
1952
1953         Map<String, Property> groupProperties = vfcInstanceEntity.getProperties();
1954
1955         for (String key : groupProperties.keySet()) {
1956             Property property = groupProperties.get(key);
1957
1958             String vfcName = property.getName();
1959
1960             if (vfcName != null) {
1961                 if (vfcName.equals("vfc_instance_group_function")) {
1962
1963                     String vfcValue = property.getValue().toString();
1964                     int getInputIndex = vfcValue.indexOf("{get_input=");
1965                     if (getInputIndex > -1) {
1966                         getInputName = vfcValue.substring(getInputIndex + 11, vfcValue.length() - 1);
1967                     }
1968
1969                 }
1970             }
1971
1972         }
1973
1974         List<IEntityDetails> serviceEntityList = getEntityDetails(toscaResourceStructure,
1975                 EntityQuery.newBuilder(SdcTypes.VF)
1976                         .customizationUUID(vnfResourceCustomization.getModelCustomizationUUID()),
1977                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false);
1978
1979         if (serviceEntityList != null && !serviceEntityList.isEmpty()) {
1980             vfcInstanceGroupCustom.setFunction(getLeafPropertyValue(serviceEntityList.get(0), getInputName));
1981         }
1982
1983         vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
1984
1985         List<Input> inputs = vfEntityDetails.getInputs();
1986
1987         createVFCInstanceGroupMembers(vfcInstanceGroupCustom, vfcInstanceEntity, inputs, existingVnfcGroupSet);
1988
1989         return vfcInstanceGroupCustom;
1990     }
1991
1992     private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom,
1993             IEntityDetails vfcModuleEntity, List<Input> inputList, Set<VnfcCustomization> existingVnfcGroupSet) {
1994         List<IEntityDetails> members = vfcModuleEntity.getMemberNodes();
1995         if (!CollectionUtils.isEmpty(members)) {
1996             for (IEntityDetails vfcEntity : members) {
1997
1998                 VnfcCustomization existingVfcGroup = findExistingVfc(existingVnfcGroupSet,
1999                         vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2000
2001                 if (existingVfcGroup == null) {
2002                     VnfcCustomization vnfcCustomization = new VnfcCustomization();
2003
2004                     Metadata metadata = vfcEntity.getMetadata();
2005                     vnfcCustomization.setModelCustomizationUUID(
2006                             metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2007                     vnfcCustomization.setModelInstanceName(vfcEntity.getName());
2008                     vnfcCustomization.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2009                     vnfcCustomization
2010                             .setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
2011                     vnfcCustomization.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
2012                     vnfcCustomization.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
2013                     vnfcCustomization.setToscaNodeType(testNull(vfcEntity.getToscaType()));
2014                     vnfcCustomization
2015                             .setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2016                     vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcEntity, inputList));
2017                     vnfcCustomization.setVnfcInstanceGroupCustomization(vfcInstanceGroupCustom);
2018                     List<VnfcCustomization> vnfcCustomizations = vfcInstanceGroupCustom.getVnfcCustomizations();
2019
2020                     if (vnfcCustomizations == null) {
2021                         vnfcCustomizations = new ArrayList<>();
2022                         vfcInstanceGroupCustom.setVnfcCustomizations(vnfcCustomizations);
2023                     }
2024                     vnfcCustomizations.add(vnfcCustomization);
2025
2026                     existingVnfcGroupSet.add(vnfcCustomization);
2027                 }
2028             }
2029         }
2030     }
2031
2032     public String getVnfcResourceInput(IEntityDetails vfcEntity, List<Input> inputList) {
2033         Map<String, String> resouceRequest = new HashMap<>();
2034         Map<String, Property> vfcTemplateProperties = vfcEntity.getProperties();
2035         for (String key : vfcTemplateProperties.keySet()) {
2036             Property property = vfcTemplateProperties.get(key);
2037             String resourceValue = getValue(property.getValue(), inputList);
2038             resouceRequest.put(key, resourceValue);
2039         }
2040
2041         String resourceCustomizationUuid =
2042                 vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
2043
2044         String jsonStr = null;
2045         try {
2046             ObjectMapper objectMapper = new ObjectMapper();
2047             jsonStr = objectMapper.writeValueAsString(resouceRequest);
2048             jsonStr = jsonStr.replace("\"", "\\\"");
2049             logger.debug("vfcResource request for resource customization id {}: {}", resourceCustomizationUuid,
2050                     jsonStr);
2051         } catch (JsonProcessingException e) {
2052             logger.debug("Json Exception: {}", e.getMessage());
2053             logger.error("Exception occurred", e);
2054         }
2055
2056         return jsonStr;
2057     }
2058
2059     protected VfModuleCustomization createVFModuleResource(IEntityDetails vfModuleEntityDetails,
2060             ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure,
2061             IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service,
2062             Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet,
2063             List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom) {
2064
2065         VfModuleCustomization vfModuleCustomization =
2066                 findExistingVfModuleCustomization(vnfResource, vfModuleData.getVfModuleModelCustomizationUUID());
2067
2068         if (vfModuleCustomization == null) {
2069
2070             VfModule vfModule = findExistingVfModule(vnfResource,
2071                     vfModuleEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
2072
2073             Metadata vfMetadata = vfModuleEntityDetails.getMetadata();
2074             if (vfModule == null)
2075                 vfModule = createVfModule(vfModuleEntityDetails, toscaResourceStructure, vfModuleData, vfMetadata);
2076
2077             vfModuleCustomization =
2078                     createVfModuleCustomization(vfModuleEntityDetails, toscaResourceStructure, vfModule, vfModuleData);
2079             vfModuleCustomization.setVnfCustomization(vnfResource);
2080             setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization,
2081                     vfMetadata);
2082             vfModuleCustomization.setVfModule(vfModule);
2083             vfModule.getVfModuleCustomization().add(vfModuleCustomization);
2084             vnfResource.getVfModuleCustomizations().add(vfModuleCustomization);
2085         } else {
2086             vfResourceStructure.setAlreadyDeployed(true);
2087         }
2088
2089         // ******************************************************************************************************************
2090         // * Extract VFC's and CVFC's then add them to VFModule
2091         // ******************************************************************************************************************
2092
2093         List<CvnfcConfigurationCustomization> cvnfcConfigurationCustomizations = new ArrayList<>();
2094         List<CvnfcCustomization> cvnfcCustomizations = new ArrayList<>();
2095         Set<VnfcCustomization> vnfcCustomizations = new HashSet<>();
2096
2097         // Only set the CVNFC if this vfModule group is a member of it.
2098
2099         List<IEntityDetails> groupMembers = getEntityDetails(toscaResourceStructure,
2100                 EntityQuery.newBuilder("org.openecomp.groups.VfModule")
2101                         .uUID(vfModuleCustomization.getVfModule().getModelUUID()),
2102                 TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);
2103
2104         String vfModuleMemberName = null;
2105
2106         // Extract CVFC lists
2107         List<IEntityDetails> cvnfcEntityList = getEntityDetails(toscaResourceStructure,
2108                 EntityQuery.newBuilder(SdcTypes.CVFC), TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);
2109
2110
2111         for (IEntityDetails cvfcEntity : cvnfcEntityList) {
2112             boolean cvnfcVfModuleNameMatch = false;
2113
2114             for (IEntityDetails entity : groupMembers) {
2115
2116                 List<IEntityDetails> groupMembersNodes = entity.getMemberNodes();
2117                 for (IEntityDetails groupMember : groupMembersNodes) {
2118
2119                     vfModuleMemberName = groupMember.getName();
2120
2121                     if (vfModuleMemberName.equalsIgnoreCase(cvfcEntity.getName())) {
2122                         cvnfcVfModuleNameMatch = true;
2123                         break;
2124                     }
2125
2126                 }
2127             }
2128
2129
2130             if (vfModuleMemberName != null && cvnfcVfModuleNameMatch) {
2131
2132                 // Extract associated VFC - Should always be just one
2133                 List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStructure,
2134                         EntityQuery.newBuilder(SdcTypes.VFC),
2135                         TopologyTemplateQuery.newBuilder(SdcTypes.CVFC).customizationUUID(
2136                                 cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)),
2137                         false);
2138
2139
2140                 for (IEntityDetails vfcEntity : vfcEntityList) {
2141
2142                     VnfcCustomization vnfcCustomization = new VnfcCustomization();
2143                     VnfcCustomization existingVnfcCustomization = null;
2144
2145                     existingVnfcCustomization = findExistingVfc(existingVnfcSet,
2146                             vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2147
2148                     if (existingVnfcCustomization == null) {
2149                         vnfcCustomization = new VnfcCustomization();
2150                     } else {
2151                         vnfcCustomization = existingVnfcCustomization;
2152                     }
2153
2154                     // Only Add Abstract VNFC's to our DB, ignore all others
2155                     if (existingVnfcCustomization == null && vfcEntity.getMetadata()
2156                             .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) {
2157
2158                         vnfcCustomization.setModelCustomizationUUID(
2159                                 vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2160                         vnfcCustomization.setModelInstanceName(vfcEntity.getName());
2161                         vnfcCustomization.setModelInvariantUUID(
2162                                 vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
2163                         vnfcCustomization
2164                                 .setModelName(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
2165                         vnfcCustomization
2166                                 .setModelUUID(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2167
2168                         vnfcCustomization.setModelVersion(
2169                                 testNull(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2170                         vnfcCustomization.setDescription(
2171                                 testNull(vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2172                         vnfcCustomization.setToscaNodeType(testNull(vfcEntity.getToscaType()));
2173
2174                         vnfcCustomizations.add(vnfcCustomization);
2175                         existingVnfcSet.add(vnfcCustomization);
2176                     }
2177
2178                     // This check is needed incase the VFC subcategory is
2179                     // something other than Abstract. In that case we want to
2180                     // skip adding that record to our DB.
2181                     if (vnfcCustomization.getModelCustomizationUUID() != null) {
2182                         CvnfcCustomization cvnfcCustomization = new CvnfcCustomization();
2183                         cvnfcCustomization.setModelCustomizationUUID(
2184                                 cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2185                         cvnfcCustomization.setModelInstanceName(cvfcEntity.getName());
2186                         cvnfcCustomization.setModelInvariantUUID(
2187                                 cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
2188                         cvnfcCustomization
2189                                 .setModelName(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
2190                         cvnfcCustomization
2191                                 .setModelUUID(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2192
2193                         cvnfcCustomization.setModelVersion(
2194                                 testNull(cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2195                         cvnfcCustomization.setDescription(testNull(
2196                                 cvfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2197                         cvnfcCustomization.setToscaNodeType(testNull(cvfcEntity.getToscaType()));
2198
2199                         if (existingVnfcCustomization != null) {
2200                             cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization);
2201                         } else {
2202                             cvnfcCustomization.setVnfcCustomization(vnfcCustomization);
2203                         }
2204
2205                         cvnfcCustomization.setNfcFunction(getLeafPropertyValue(cvfcEntity, "nfc_function"));
2206                         cvnfcCustomization.setNfcNamingCode(getLeafPropertyValue(cvfcEntity, "nfc_naming_code"));
2207
2208                         cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization);
2209
2210                         // *****************************************************************************************************************************************
2211                         // * Extract Fabric Configuration
2212                         // *****************************************************************************************************************************************
2213
2214                         List<IEntityDetails> fabricEntityList =
2215                                 getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.CONFIGURATION),
2216                                         TopologyTemplateQuery.newBuilder(SdcTypes.VF), false);
2217
2218                         for (IEntityDetails fabricEntity : fabricEntityList) {
2219
2220                             List<RequirementAssignment> requirements = fabricEntity.getRequirements();
2221
2222                             for (RequirementAssignment requirement : requirements) {
2223
2224                                 if (requirement.getNodeTemplateName().equals(cvfcEntity.getName())) {
2225
2226                                     ConfigurationResource fabricConfig = null;
2227
2228                                     ConfigurationResource existingConfig = findExistingConfiguration(
2229                                             existingCvnfcConfigurationCustom,
2230                                             fabricEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2231
2232                                     if (existingConfig == null) {
2233
2234                                         fabricConfig = createFabricConfiguration(fabricEntity, toscaResourceStructure);
2235
2236                                     } else {
2237                                         fabricConfig = existingConfig;
2238                                     }
2239
2240                                     CvnfcConfigurationCustomization cvnfcConfigurationCustomization =
2241                                             createCvnfcConfigurationCustomization(fabricEntity, toscaResourceStructure,
2242                                                     vnfResource, vfModuleCustomization, cvnfcCustomization,
2243                                                     fabricConfig, vfModuleMemberName);
2244
2245                                     cvnfcConfigurationCustomizations.add(cvnfcConfigurationCustomization);
2246
2247                                     existingCvnfcConfigurationCustom.add(cvnfcConfigurationCustomization);
2248
2249                                 }
2250                             }
2251
2252                         }
2253                         cvnfcCustomization.setCvnfcConfigurationCustomization(cvnfcConfigurationCustomizations);
2254                         cvnfcCustomizations.add(cvnfcCustomization);
2255                         existingCvnfcSet.add(cvnfcCustomization);
2256
2257                     }
2258
2259                 }
2260
2261             }
2262         }
2263         vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations);
2264
2265         return vfModuleCustomization;
2266     }
2267
2268     protected CvnfcConfigurationCustomization createCvnfcConfigurationCustomization(IEntityDetails fabricEntity,
2269             ToscaResourceStructure toscaResourceStruct, VnfResourceCustomization vnfResource,
2270             VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization,
2271             ConfigurationResource configResource, String vfModuleMemberName) {
2272
2273         Metadata fabricMetadata = fabricEntity.getMetadata();
2274
2275         CvnfcConfigurationCustomization cvnfcConfigurationCustomization = new CvnfcConfigurationCustomization();
2276
2277         cvnfcConfigurationCustomization.setConfigurationResource(configResource);
2278
2279         cvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization);
2280
2281         cvnfcConfigurationCustomization
2282                 .setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2283         cvnfcConfigurationCustomization.setModelInstanceName(fabricEntity.getName());
2284
2285         cvnfcConfigurationCustomization.setConfigurationFunction(getLeafPropertyValue(fabricEntity, "function"));
2286         cvnfcConfigurationCustomization.setConfigurationRole(getLeafPropertyValue(fabricEntity, "role"));
2287         cvnfcConfigurationCustomization.setConfigurationType(getLeafPropertyValue(fabricEntity, "type"));
2288
2289         return cvnfcConfigurationCustomization;
2290     }
2291
2292     protected ConfigurationResource findExistingConfiguration(
2293             List<CvnfcConfigurationCustomization> existingCvnfcConfigurationCustom, String modelUUID) {
2294         ConfigurationResource configResource = null;
2295         for (CvnfcConfigurationCustomization cvnfcConfigCustom : existingCvnfcConfigurationCustom) {
2296             if (cvnfcConfigCustom != null) {
2297                 if (cvnfcConfigCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
2298                     configResource = cvnfcConfigCustom.getConfigurationResource();
2299                 }
2300             }
2301         }
2302
2303         return configResource;
2304     }
2305
2306     protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID,
2307             List<ConfigurationResourceCustomization> configurationResourceList) {
2308         ConfigurationResource configResource = null;
2309         for (ConfigurationResourceCustomization configurationResourceCustom : configurationResourceList) {
2310             if (configurationResourceCustom.getConfigurationResource() != null
2311                     && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) {
2312                 configResource = configurationResourceCustom.getConfigurationResource();
2313             }
2314         }
2315
2316         return configResource;
2317     }
2318
2319     protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource,
2320             String vfModuleModelCustomizationUUID) {
2321         VfModuleCustomization vfModuleCustomization = null;
2322         for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
2323             if (vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)) {
2324                 vfModuleCustomization = vfModuleCustom;
2325             }
2326         }
2327         return vfModuleCustomization;
2328     }
2329
2330     protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) {
2331         VfModule vfModule = null;
2332         for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) {
2333             if (vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)) {
2334                 vfModule = vfModuleCustom.getVfModule();
2335             }
2336         }
2337         if (vfModule == null)
2338             vfModule = vfModuleRepo.findByModelUUID(modelUUID);
2339
2340         return vfModule;
2341     }
2342
2343     protected VfModuleCustomization createVfModuleCustomization(IEntityDetails vfModuleEntityDetails,
2344             ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) {
2345         VfModuleCustomization vfModuleCustomization = new VfModuleCustomization();
2346
2347         vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID());
2348
2349         vfModuleCustomization.setVfModule(vfModule);
2350
2351         String initialCount = getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT);
2352
2353
2354         if (initialCount != null && initialCount.length() > 0) {
2355             vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount));
2356         }
2357
2358         String availabilityZoneCount =
2359                 getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT);
2360
2361         if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) {
2362             vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount));
2363         }
2364
2365         vfModuleCustomization
2366                 .setLabel(getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL));
2367
2368         String maxInstances =
2369                 getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES);
2370
2371         if (maxInstances != null && maxInstances.length() > 0) {
2372             vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances));
2373         }
2374
2375         String minInstances =
2376                 getLeafPropertyValue(vfModuleEntityDetails, SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES);
2377
2378         if (minInstances != null && minInstances.length() > 0) {
2379             vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances));
2380         }
2381
2382         String skipPostInstConfText = getLeafPropertyValue(vfModuleEntityDetails, SKIP_POST_INST_CONF);
2383
2384         if (skipPostInstConfText != null) {
2385             vfModuleCustomization.setSkipPostInstConf(
2386                     Boolean.parseBoolean(getLeafPropertyValue(vfModuleEntityDetails, SKIP_POST_INST_CONF)));
2387         }
2388
2389         return vfModuleCustomization;
2390     }
2391
2392     protected VfModule createVfModule(IEntityDetails groupEntityDetails, ToscaResourceStructure toscaResourceStructure,
2393             IVfModuleData vfModuleData, Metadata vfMetadata) {
2394         VfModule vfModule = new VfModule();
2395         String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID();
2396
2397         if (vfModuleModelUUID == null) {
2398
2399             vfModuleModelUUID = testNull(
2400                     groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID));
2401
2402         } else if (vfModuleModelUUID.indexOf('.') > -1) {
2403             vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.'));
2404         }
2405
2406         vfModule.setModelInvariantUUID(
2407                 groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID));
2408         vfModule.setModelName(
2409                 groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME));
2410         vfModule.setModelUUID(vfModuleModelUUID);
2411         vfModule.setModelVersion(
2412                 groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION));
2413         vfModule.setDescription(groupEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
2414
2415         String vfModuleType = getLeafPropertyValue(groupEntityDetails, SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE);
2416
2417         if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) {
2418             vfModule.setIsBase(true);
2419         } else {
2420             vfModule.setIsBase(false);
2421         }
2422         return vfModule;
2423     }
2424
2425     protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure,
2426             VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization,
2427             Metadata vfMetadata) {
2428
2429         Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream()
2430                 .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID()
2431                         .equalsIgnoreCase(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)))
2432                 .findFirst();
2433
2434         if (matchingObject.isPresent()) {
2435             List<HeatFiles> heatFilesList = new ArrayList<>();
2436             List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<>();
2437             List<HeatTemplate> heatChildTemplates = new ArrayList<>();
2438             HeatTemplate parentHeatTemplate = new HeatTemplate();
2439             String parentArtifactType = null;
2440             Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts());
2441             for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) {
2442
2443                 List<HeatTemplate> childNestedHeatTemplates = new ArrayList<>();
2444
2445                 if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) {
2446                     checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact,
2447                             childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure);
2448                 }
2449
2450                 if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
2451                     parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact);
2452
2453                     if (!childNestedHeatTemplates.isEmpty()) {
2454
2455                         if (parentArtifactType != null
2456                                 && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) {
2457                             volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0));
2458                         } else {
2459                             heatChildTemplates.add(childNestedHeatTemplates.get(0));
2460                         }
2461                     }
2462                 }
2463
2464             }
2465             if (!heatFilesList.isEmpty()) {
2466                 vfModule.setHeatFiles(heatFilesList);
2467             }
2468
2469
2470             // Set all Child Templates related to HEAT_VOLUME
2471             if (!volumeHeatChildTemplates.isEmpty()) {
2472                 if (vfModule.getVolumeHeatTemplate() != null) {
2473                     vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates);
2474                 } else {
2475                     logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()");
2476                 }
2477             }
2478
2479             // Set all Child Templates related to HEAT
2480             if (!heatChildTemplates.isEmpty()) {
2481                 if (vfModule.getModuleHeatTemplate() != null) {
2482                     vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates);
2483                 } else {
2484                     logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()");
2485                 }
2486             }
2487         }
2488     }
2489
2490     protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization,
2491             List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates,
2492             HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) {
2493         if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) {
2494             vfModuleArtifact.incrementDeployedInDB();
2495             vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate());
2496         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) {
2497             vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate());
2498             VfModuleArtifact volVfModuleArtifact =
2499                     this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact);
2500             vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment());
2501             vfModuleArtifact.incrementDeployedInDB();
2502         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) {
2503             if (vfModuleArtifact.getHeatEnvironment() != null) {
2504                 if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) {
2505                     vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment());
2506                 } else {
2507                     vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment());
2508                 }
2509             }
2510             vfModuleArtifact.incrementDeployedInDB();
2511         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) {
2512             heatFilesList.add(vfModuleArtifact.getHeatFiles());
2513             vfModuleArtifact.incrementDeployedInDB();
2514         } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) {
2515             nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate());
2516             vfModuleArtifact.incrementDeployedInDB();
2517         }
2518     }
2519
2520     protected VnfResourceCustomization createVnfResource(IEntityDetails entityDetails,
2521             ToscaResourceStructure toscaResourceStructure, Service service) throws ArtifactInstallerException {
2522         VnfResourceCustomization vnfResourceCustomization = null;
2523         if (vnfResourceCustomization == null) {
2524
2525             VnfResource vnfResource = findExistingVnfResource(service,
2526                     entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2527
2528             if (vnfResource == null) {
2529                 vnfResource = createVnfResource(entityDetails);
2530             }
2531
2532             vnfResourceCustomization =
2533                     createVnfResourceCustomization(entityDetails, toscaResourceStructure, vnfResource);
2534             vnfResourceCustomization.setVnfResources(vnfResource);
2535             vnfResourceCustomization.setService(service);
2536
2537             // setting resource input for vnf customization
2538             vnfResourceCustomization.setResourceInput(
2539                     getResourceInput(toscaResourceStructure, vnfResourceCustomization.getModelCustomizationUUID()));
2540
2541         }
2542         return vnfResourceCustomization;
2543     }
2544
2545     protected VnfResource findExistingVnfResource(Service service, String modelUUID) {
2546         VnfResource vnfResource = null;
2547         for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
2548             if (vnfResourceCustom.getVnfResources() != null
2549                     && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) {
2550                 vnfResource = vnfResourceCustom.getVnfResources();
2551             }
2552         }
2553         if (vnfResource == null)
2554             vnfResource = vnfRepo.findResourceByModelUUID(modelUUID);
2555
2556         return vnfResource;
2557     }
2558
2559     protected VnfResourceCustomization createVnfResourceCustomization(IEntityDetails entityDetails,
2560             ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) {
2561         VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization();
2562         vnfResourceCustomization.setModelCustomizationUUID(
2563                 entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2564
2565         vnfResourceCustomization.setModelInstanceName(entityDetails.getName());
2566         vnfResourceCustomization
2567                 .setNfFunction(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
2568         vnfResourceCustomization.setNfNamingCode(getLeafPropertyValue(entityDetails, "nf_naming_code"));
2569         vnfResourceCustomization.setNfRole(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFROLE));
2570         vnfResourceCustomization.setNfType(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
2571
2572         vnfResourceCustomization.setMultiStageDesign(getLeafPropertyValue(entityDetails, MULTI_STAGE_DESIGN));
2573         vnfResourceCustomization.setBlueprintName(getLeafPropertyValue(entityDetails, SDNC_MODEL_NAME));
2574         vnfResourceCustomization.setBlueprintVersion(getLeafPropertyValue(entityDetails, SDNC_MODEL_VERSION));
2575
2576         String skipPostInstConfText = getLeafPropertyValue(entityDetails, SKIP_POST_INST_CONF);
2577
2578         if (skipPostInstConfText != null) {
2579             vnfResourceCustomization.setSkipPostInstConf(
2580                     Boolean.parseBoolean(getLeafPropertyValue(entityDetails, SKIP_POST_INST_CONF)));
2581         }
2582
2583         vnfResourceCustomization.setControllerActor(getLeafPropertyValue(entityDetails, CONTROLLER_ACTOR));
2584         vnfResourceCustomization.setVnfResources(vnfResource);
2585         vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger(
2586                 entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT)));
2587
2588         List<CapabilityAssignment> capAssignList = entityDetails.getCapabilities();
2589
2590         if (capAssignList != null) {
2591
2592             for (CapabilityAssignment capAssign : capAssignList) {
2593
2594
2595                 if (capAssign != null) {
2596
2597                     String capabilityName = capAssign.getName();
2598
2599                     if (capabilityName.equalsIgnoreCase(SCALABLE)) {
2600                         vnfResourceCustomization.setMinInstances(Integer.getInteger(
2601                                 getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2602                         vnfResourceCustomization.setMaxInstances(Integer.getInteger(
2603                                 getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2604                     }
2605                 }
2606
2607             }
2608         }
2609
2610         if (vnfResourceCustomization.getMinInstances() == null && vnfResourceCustomization.getMaxInstances() == null) {
2611             vnfResourceCustomization.setMinInstances(Integer
2612                     .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2613             vnfResourceCustomization.setMaxInstances(Integer
2614                     .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2615         }
2616
2617         toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization);
2618
2619         return vnfResourceCustomization;
2620     }
2621
2622     protected VnfResource createVnfResource(IEntityDetails entityDetails) {
2623         VnfResource vnfResource = new VnfResource();
2624         vnfResource.setModelInvariantUUID(
2625                 testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
2626         vnfResource.setModelName(testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
2627         vnfResource.setModelUUID(testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
2628
2629         vnfResource.setModelVersion(
2630                 testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2631         vnfResource.setDescription(
2632                 testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
2633         vnfResource.setOrchestrationMode(HEAT);
2634         vnfResource.setToscaNodeType(testNull(entityDetails.getToscaType()));
2635         vnfResource.setAicVersionMax(
2636                 testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2637         vnfResource.setAicVersionMin(
2638                 testNull(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2639         vnfResource.setCategory(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY));
2640         vnfResource.setSubCategory(entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY));
2641
2642         return vnfResource;
2643     }
2644
2645     protected AllottedResourceCustomization createAllottedResource(IEntityDetails arEntity,
2646             ToscaResourceStructure toscaResourceStructure, Service service) {
2647         AllottedResourceCustomization allottedResourceCustomization =
2648                 allottedCustomizationRepo.findOneByModelCustomizationUUID(
2649                         arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
2650
2651         if (allottedResourceCustomization == null) {
2652             AllottedResource allottedResource = findExistingAllottedResource(service,
2653                     arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2654
2655             if (allottedResource == null)
2656                 allottedResource = createAR(arEntity);
2657
2658             toscaResourceStructure.setAllottedResource(allottedResource);
2659             allottedResourceCustomization = createAllottedResourceCustomization(arEntity, toscaResourceStructure);
2660             allottedResourceCustomization.setAllottedResource(allottedResource);
2661             allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization);
2662         }
2663         return allottedResourceCustomization;
2664     }
2665
2666     protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) {
2667         AllottedResource allottedResource = null;
2668         for (AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()) {
2669             if (allottedResourceCustom.getAllottedResource() != null
2670                     && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) {
2671                 allottedResource = allottedResourceCustom.getAllottedResource();
2672             }
2673         }
2674         if (allottedResource == null)
2675             allottedResource = allottedRepo.findResourceByModelUUID(modelUUID);
2676
2677         return allottedResource;
2678     }
2679
2680     protected AllottedResourceCustomization createAllottedResourceCustomization(IEntityDetails arEntity,
2681             ToscaResourceStructure toscaResourceStructure) {
2682         AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization();
2683         allottedResourceCustomization.setModelCustomizationUUID(
2684                 testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)));
2685         allottedResourceCustomization.setModelInstanceName(arEntity.getName());
2686
2687         allottedResourceCustomization
2688                 .setNfFunction(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION));
2689         allottedResourceCustomization.setNfNamingCode(getLeafPropertyValue(arEntity, "nf_naming_code"));
2690         allottedResourceCustomization.setNfRole(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFROLE));
2691         allottedResourceCustomization.setNfType(getLeafPropertyValue(arEntity, SdcPropertyNames.PROPERTY_NAME_NFTYPE));
2692
2693         EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.VFC).build();
2694
2695         TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.VF)
2696                 .customizationUUID(allottedResourceCustomization.getModelCustomizationUUID()).build();
2697
2698         List<IEntityDetails> vfcEntities =
2699                 toscaResourceStructure.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, false);
2700
2701
2702         if (vfcEntities != null) {
2703             for (IEntityDetails vfcEntity : vfcEntities) {
2704
2705                 allottedResourceCustomization
2706                         .setProvidingServiceModelUUID(getLeafPropertyValue(vfcEntity, "providing_service_uuid"));
2707                 allottedResourceCustomization.setProvidingServiceModelInvariantUUID(
2708                         getLeafPropertyValue(vfcEntity, "providing_service_invariant_uuid"));
2709                 allottedResourceCustomization
2710                         .setProvidingServiceModelName(getLeafPropertyValue(vfcEntity, "providing_service_name"));
2711             }
2712         }
2713
2714         List<CapabilityAssignment> capAssignmentList = arEntity.getCapabilities();
2715
2716         if (capAssignmentList != null) {
2717
2718             for (CapabilityAssignment arCapability : capAssignmentList) {
2719
2720                 if (arCapability != null) {
2721
2722                     String capabilityName = arCapability.getName();
2723
2724                     if (capabilityName.equals(SCALABLE)) {
2725
2726                         allottedResourceCustomization
2727                                 .setMinInstances(Integer.getInteger(getCapabilityLeafPropertyValue(arCapability,
2728                                         SdcPropertyNames.PROPERTY_NAME_MININSTANCES)));
2729                         allottedResourceCustomization
2730                                 .setMinInstances(Integer.getInteger(getCapabilityLeafPropertyValue(arCapability,
2731                                         SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)));
2732
2733                     }
2734                 }
2735
2736             }
2737         }
2738
2739         return allottedResourceCustomization;
2740     }
2741
2742     protected AllottedResource createAR(IEntityDetails arEntity) {
2743         AllottedResource allottedResource = new AllottedResource();
2744         allottedResource.setModelUUID(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)));
2745         allottedResource.setModelInvariantUUID(
2746                 testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)));
2747         allottedResource.setModelName(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)));
2748         allottedResource
2749                 .setModelVersion(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)));
2750         allottedResource.setToscaNodeType(testNull(arEntity.getToscaType()));
2751         allottedResource
2752                 .setSubcategory(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)));
2753         allottedResource.setDescription(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
2754         return allottedResource;
2755     }
2756
2757     protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) {
2758         // Scan the payload downloadResult and extract the HeatTemplate
2759         // parameters
2760         YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes());
2761         return yamlEditor.getParameterList(artifactUUID);
2762     }
2763
2764     protected String testNull(Object object) {
2765
2766         if (object == null) {
2767             return null;
2768         } else if ("NULL".equals(object)) {
2769             return null;
2770         } else if (object instanceof Integer) {
2771             return object.toString();
2772         } else if (object instanceof String) {
2773             return (String) object;
2774         } else {
2775             return "Type not recognized";
2776         }
2777     }
2778
2779     protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure,
2780             VfModuleArtifact heatNestedArtifact) {
2781
2782         if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure
2783                 .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) {
2784             for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0)
2785                     .getArtifactInfo().getRelatedArtifacts()) {
2786                 if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
2787                     return ASDCConfiguration.HEAT;
2788                 }
2789
2790             }
2791         }
2792
2793         if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null
2794                 && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo()
2795                         .getRelatedArtifacts() != null) {
2796             for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL)
2797                     .get(0).getArtifactInfo().getRelatedArtifacts()) {
2798                 if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) {
2799                     return ASDCConfiguration.HEAT_VOL;
2800                 }
2801
2802             }
2803         }
2804
2805         // Does not belong to anything
2806         return null;
2807
2808     }
2809
2810     protected static String createVNFName(VfResourceStructure vfResourceStructure) {
2811
2812         return vfResourceStructure.getNotification().getServiceName() + "/"
2813                 + vfResourceStructure.getResourceInstance().getResourceInstanceName();
2814     }
2815
2816     protected static String createVfModuleName(VfModuleStructure vfModuleStructure) {
2817
2818         return createVNFName(vfModuleStructure.getParentVfResource()) + "::"
2819                 + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName();
2820     }
2821
2822     public List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct,
2823             EntityQueryBuilder entityType, TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) {
2824
2825         EntityQuery entityQuery = entityType.build();
2826         TopologyTemplateQuery topologyTemplateQuery = topologyTemplateBuilder.build();
2827         List<IEntityDetails> entityDetails =
2828                 toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch);
2829
2830         return entityDetails;
2831
2832     }
2833
2834     public String getLeafPropertyValue(IEntityDetails entityDetails, String propName) {
2835
2836         Property leafProperty = entityDetails.getProperties().get(propName);
2837
2838         if (leafProperty != null && leafProperty.getValue() != null) {
2839             return leafProperty.getValue().toString();
2840         }
2841
2842         return null;
2843     }
2844
2845     protected String getCapabilityLeafPropertyValue(CapabilityAssignment capAssign, String propName) {
2846
2847         Property leafProperty = capAssign.getProperties().get(propName);
2848
2849         if (leafProperty != null && leafProperty.getValue() != null) {
2850             return leafProperty.getValue().toString();
2851         }
2852
2853         return null;
2854     }
2855
2856     protected String getPropertyInput(String propertyName) {
2857
2858         String inputName = new String();
2859
2860         if (propertyName != null) {
2861             int getInputIndex = propertyName.indexOf("{get_input=");
2862             int getClosingIndex = propertyName.indexOf("}");
2863             if (getInputIndex > -1) {
2864                 inputName = propertyName.substring(getInputIndex + 11, getClosingIndex);
2865             }
2866         }
2867
2868         return inputName;
2869     }
2870
2871     // this method add provided vnfCustomization to service with
2872     // existing customization available in db.
2873     private void addVnfCustomization(Service service, VnfResourceCustomization vnfResourceCustomization) {
2874         List<Service> services = serviceRepo.findByModelUUID(service.getModelUUID());
2875         if (!services.isEmpty()) {
2876             // service exist in db
2877             Service existingService = services.get(0);
2878             List<VnfResourceCustomization> existingVnfCustomizations = existingService.getVnfCustomizations();
2879             if (existingService != null) {
2880                 // it is duplicating entries, so added a check
2881                 for (VnfResourceCustomization existingVnfResourceCustomization : existingVnfCustomizations) {
2882                     if (!service.getVnfCustomizations().contains(existingVnfResourceCustomization)) {
2883                         service.getVnfCustomizations().add(existingVnfResourceCustomization);
2884                     }
2885                 }
2886             }
2887         }
2888         service.getVnfCustomizations().add(vnfResourceCustomization);
2889
2890     }
2891
2892
2893     protected static Timestamp getCurrentTimeStamp() {
2894
2895         return new Timestamp(new Date().getTime());
2896     }
2897
2898     private String getServiceInput(ToscaResourceStructure toscaResourceStructure) {
2899         String serviceInput = null;
2900
2901         List<Object> serviceInputList;
2902         ISdcCsarHelper sdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
2903         List<Input> serviceInputs = sdcCsarHelper.getServiceInputs();
2904         if (!serviceInputs.isEmpty()) {
2905             serviceInputList = new ArrayList<>();
2906             List<Input> filterList;
2907             filterList = serviceInputs.stream()
2908                     .filter(input -> !SKIP_POST_INST_CONF.equals(input.getName())
2909                             && !CDS_MODEL_NAME.equalsIgnoreCase(input.getName())
2910                             && !CDS_MODEL_VERSION.equalsIgnoreCase(input.getName())
2911                             && !CONTROLLER_ACTOR.equalsIgnoreCase(input.getName()))
2912                     .collect(Collectors.toList());
2913
2914             filterList.forEach(input -> {
2915                 Map<String, Object> serviceInputMap = new HashMap<>();
2916                 serviceInputMap.put("name", input.getName());
2917                 serviceInputMap.put("type", input.getType());
2918                 serviceInputMap.put("default", input.getDefault() == null ? "" : input.getDefault());
2919                 serviceInputMap.put("required", input.isRequired());
2920                 serviceInputList.add(serviceInputMap);
2921
2922             });
2923             ObjectMapper objectMapper = new ObjectMapper();
2924             try {
2925                 serviceInput = objectMapper.writeValueAsString(serviceInputList);
2926                 serviceInput = serviceInput.replace("\"", "\\\"");
2927             } catch (JsonProcessingException e) {
2928                 logger.error("service input could not be deserialized for service uuid:  "
2929                         + sdcCsarHelper.getServiceMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
2930             }
2931         } else {
2932             logger.debug("serviceInput is null");
2933         }
2934         return serviceInput;
2935     }
2936
2937     @Transactional(rollbackFor = {ArtifactInstallerException.class})
2938     public void installNsstService(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct,
2939             String artifactContent) {
2940         createToscaCsar(toscaResourceStruct);
2941         createService(toscaResourceStruct, vfResourceStruct);
2942         Service service = toscaResourceStruct.getCatalogService();
2943         createServiceInfo(toscaResourceStruct, service);
2944         createServiceArtifact(service, vfResourceStruct, artifactContent);
2945         serviceRepo.save(service);
2946     }
2947
2948     private void createServiceArtifact(Service service, VfResourceStructure vfResourceStruct, String artifactContent) {
2949         if (null == vfResourceStruct) {
2950             return;
2951         }
2952         List<ServiceArtifact> serviceArtifactList = new ArrayList<>();
2953         ServiceArtifact serviceArtifact;
2954         List<IArtifactInfo> artifactInfoList = vfResourceStruct.getNotification().getServiceArtifacts().stream()
2955                 .filter(artifact -> artifact.getArtifactType().equalsIgnoreCase("WORKFLOW"))
2956                 .collect(Collectors.toList());
2957         for (IArtifactInfo artifactInfo : artifactInfoList) {
2958             serviceArtifact = new ServiceArtifact();
2959             serviceArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
2960             serviceArtifact.setName(artifactInfo.getArtifactName());
2961             serviceArtifact.setType("OTHER");
2962             serviceArtifact.setVersion(artifactInfo.getArtifactVersion());
2963             serviceArtifact.setDescription(artifactInfo.getArtifactDescription());
2964             serviceArtifact.setChecksum(artifactInfo.getArtifactChecksum());
2965             serviceArtifact.setContent(artifactContent);
2966             serviceArtifact.setService(service);
2967             serviceArtifactList.add(serviceArtifact);
2968         }
2969         service.setServiceArtifactList(serviceArtifactList);
2970     }
2971
2972     private void createServiceInfo(ToscaResourceStructure toscaResourceStruct, Service service) {
2973         if (!service.getServiceInfos().isEmpty()) {
2974             return;
2975         }
2976
2977         List<ServiceInfo> serviceInfos = new ArrayList<>();
2978
2979         ServiceInfo serviceInfo = new ServiceInfo();
2980         String serviceInput = getServiceInput(toscaResourceStruct);
2981         serviceInfo.setServiceInput(serviceInput);
2982
2983         String serviceProperties = getServiceProperties(toscaResourceStruct);
2984         serviceInfo.setServiceProperties(serviceProperties);
2985         serviceInfo.setService(service);
2986         serviceInfos.add(serviceInfo);
2987
2988         service.setServiceInfos(serviceInfos);
2989     }
2990
2991     private String getServiceProperties(ToscaResourceStructure toscaResourceStruct) {
2992         String propertiesJson = null;
2993         ObjectMapper objectMapper = new ObjectMapper();
2994         ISdcCsarHelper helper = toscaResourceStruct.getSdcCsarHelper();
2995         String typeName = helper.getServiceSubstitutionMappingsTypeName();
2996         Optional<NodeTemplate> nodeTemplate = helper.getServiceNodeTemplates().stream().findAny();
2997
2998         if (nodeTemplate.isPresent()) {
2999             String serviceUUID = nodeTemplate.get().getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID);
3000             LinkedHashMap<String, Object> customDef = nodeTemplate.get().getCustomDef();
3001             List<Object> serviceProperties = getPropertiesFromCustomDef(customDef, typeName);
3002
3003             try {
3004                 propertiesJson = objectMapper.writeValueAsString(serviceProperties);
3005                 propertiesJson = propertiesJson.replace("\"", "\\\"");
3006             } catch (JsonProcessingException e) {
3007                 logger.error("serviceProperties could not be deserialized for service uuid:  " + serviceUUID);
3008             } catch (Exception ex) {
3009                 logger.error("service properties parsing failed. service uuid:" + serviceUUID);
3010             }
3011
3012         } else {
3013             logger.debug("ServiceNodeTemplates is null");
3014         }
3015         return propertiesJson;
3016     }
3017
3018     private static List<Object> getPropertiesFromCustomDef(LinkedHashMap<String, Object> customDef,
3019             final String typeName) {
3020         Optional<String> machKey =
3021                 customDef.keySet().stream().filter(key -> key.equalsIgnoreCase(typeName)).findFirst();
3022         Map<String, Object> servicePropertiesMap;
3023         List<Object> serviceProperties = new ArrayList<>();
3024
3025         if (machKey.isPresent()) {
3026             Object obj = customDef.get(machKey.get());
3027             if (obj instanceof Map) {
3028                 Object properties = ((HashMap) obj).get("properties");
3029                 if (null != properties) {
3030                     for (Object propertyName : ((Map) properties).keySet()) {
3031                         if (propertyName.toString().split("_").length >= 2) {
3032                             continue;
3033                         }
3034
3035                         servicePropertiesMap = new HashMap<>();
3036                         servicePropertiesMap.put("name", propertyName);
3037                         Object object = ((Map) properties).get(propertyName);
3038                         for (Object entry : ((Map) object).entrySet()) {
3039                             servicePropertiesMap.put((String) ((Map.Entry) entry).getKey(),
3040                                     ((Map.Entry) entry).getValue());
3041                         }
3042
3043                         String type = servicePropertiesMap.get("type").toString();
3044                         if (type.split("\\.").length >= 2) {
3045                             List<Object> subProperties = getPropertiesFromCustomDef(customDef, type);
3046                             if (subProperties.size() > 0) {
3047                                 serviceProperties.addAll(subProperties);
3048                             }
3049                             continue;
3050                         }
3051                         servicePropertiesMap.remove("description");
3052                         serviceProperties.add(servicePropertiesMap);
3053                     }
3054                 }
3055             }
3056         }
3057         return serviceProperties;
3058     }
3059 }
3060