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