Merge "description styling bug fix"
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / impl / VendorSoftwareProductManagerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.vendorsoftwareproduct.impl;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.collections4.MapUtils;
25 import org.openecomp.core.enrichment.api.EnrichmentManager;
26 import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory;
27 import org.openecomp.core.model.dao.EnrichedServiceModelDao;
28 import org.openecomp.core.model.dao.ServiceModelDao;
29 import org.openecomp.core.model.types.ServiceElement;
30 import org.openecomp.core.util.UniqueValueUtil;
31 import org.openecomp.core.utilities.file.FileContentHandler;
32 import org.openecomp.core.utilities.json.JsonSchemaDataGenerator;
33 import org.openecomp.core.utilities.json.JsonUtil;
34 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
35 import org.openecomp.core.validation.api.ValidationManager;
36 import org.openecomp.core.validation.util.MessageContainerUtil;
37 import org.openecomp.sdc.activityLog.ActivityLogManager;
38 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
39 import org.openecomp.sdc.common.errors.CoreException;
40 import org.openecomp.sdc.common.errors.ErrorCategory;
41 import org.openecomp.sdc.common.errors.ErrorCode;
42 import org.openecomp.sdc.common.errors.ValidationErrorBuilder;
43 import org.openecomp.sdc.common.utils.CommonUtil;
44 import org.openecomp.sdc.common.utils.SdcCommon;
45 import org.openecomp.sdc.datatypes.error.ErrorLevel;
46 import org.openecomp.sdc.datatypes.error.ErrorMessage;
47 import org.openecomp.sdc.generator.datatypes.tosca.VspModelInfo;
48 import org.openecomp.sdc.healing.api.HealingManager;
49 import org.openecomp.sdc.logging.api.Logger;
50 import org.openecomp.sdc.logging.api.LoggerFactory;
51 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
52 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
53 import org.openecomp.sdc.logging.messages.AuditMessages;
54 import org.openecomp.sdc.logging.types.LoggerConstants;
55 import org.openecomp.sdc.logging.types.LoggerErrorCode;
56 import org.openecomp.sdc.logging.types.LoggerServiceName;
57 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
58 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
59 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
60 import org.openecomp.sdc.validation.util.ValidationManagerUtil;
61 import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
62 import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService;
63 import org.openecomp.sdc.vendorsoftwareproduct.ManualVspToscaManager;
64 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
65 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
66 import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao;
67 import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao;
68 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao;
70 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.VendorSoftwareProductNotFoundErrorBuilder;
73 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity;
74 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity;
75 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
76 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity;
77 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity;
78 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity;
79 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
80 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity;
81 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
82 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity;
83 import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelErrorBuilder;
84 import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentErrorBuilder;
85 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
86 import org.openecomp.sdc.vendorsoftwareproduct.errors.DeploymentFlavorErrorBuilder;
87 import org.openecomp.sdc.vendorsoftwareproduct.errors.FileCreationErrorBuilder;
88 import org.openecomp.sdc.vendorsoftwareproduct.errors.InformationArtifactCreationErrorBuilder;
89 import org.openecomp.sdc.vendorsoftwareproduct.errors.NicInternalNetworkErrorBuilder;
90 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
91 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageInvalidErrorBuilder;
92 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
93 import org.openecomp.sdc.vendorsoftwareproduct.errors.TranslationFileCreationErrorBuilder;
94 import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductInvalidErrorBuilder;
95 import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory;
96 import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator;
97 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
98 import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGenerator;
99 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
100 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireValidationResult;
101 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
102 import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo;
103 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation;
104 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId;
105 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType;
106 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData;
107 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor;
108 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.NetworkType;
109 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic;
110 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComponentQuestionnaireSchemaInput;
111 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext;
112 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput;
113 import org.openecomp.sdc.vendorsoftwareproduct.utils.ComponentDependencyTracker;
114 import org.openecomp.sdc.versioning.VersioningManager;
115 import org.openecomp.sdc.versioning.VersioningUtil;
116 import org.openecomp.sdc.versioning.dao.types.Version;
117 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
118 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
119 import org.openecomp.sdc.versioning.types.VersionInfo;
120 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
121 import org.openecomp.sdcrests.activitylog.types.ActivityType;
122 import org.slf4j.MDC;
123
124 import java.io.BufferedOutputStream;
125 import java.io.ByteArrayInputStream;
126 import java.io.ByteArrayOutputStream;
127 import java.io.File;
128 import java.io.FileOutputStream;
129 import java.io.IOException;
130 import java.io.OutputStream;
131 import java.nio.ByteBuffer;
132 import java.util.ArrayList;
133 import java.util.Collection;
134 import java.util.HashMap;
135 import java.util.HashSet;
136 import java.util.List;
137 import java.util.Map;
138 import java.util.Objects;
139 import java.util.Optional;
140 import java.util.Set;
141 import java.util.zip.ZipInputStream;
142 import java.util.zip.ZipOutputStream;
143
144 public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductManager {
145   private String VALIDATION_VSP_ID = "validationOnlyVspId";
146   private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
147   //private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
148
149   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
150   private static final Logger logger =
151       LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class);
152
153   private OrchestrationTemplateDao orchestrationTemplateDao;
154   private VendorSoftwareProductInfoDao vspInfoDao;
155   private VersioningManager versioningManager;
156   private VendorSoftwareProductDao vendorSoftwareProductDao;
157   private VendorLicenseFacade vendorLicenseFacade;
158   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao;
159   private EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao;
160   private HealingManager healingManager;
161   private VendorLicenseArtifactsService licenseArtifactsService;
162   private InformationArtifactGenerator informationArtifactGenerator;
163   private PackageInfoDao packageInfoDao;
164   private ActivityLogManager activityLogManager;
165   private DeploymentFlavorDao deploymentFlavorDao;
166   private NicDao nicDao;
167   private ManualVspToscaManager manualVspToscaManager;
168
169   /**
170    * Instantiates a new Vendor software product manager.
171    *
172    * @param versioningManager            the versioning manager
173    * @param vendorSoftwareProductDao     the vendor software product dao
174    * @param orchestrationTemplateDataDao the orchestration template data dao
175    * @param vspInfoDao                   the vsp info dao
176    * @param vendorLicenseFacade          the vendor license facade
177    * @param serviceModelDao              the service model dao
178    * @param enrichedServiceModelDao      the enriched service model dao
179    * @param healingManager               the healing manager
180    * @param licenseArtifactsService      the license artifacts service
181    * @param informationArtifactGenerator the information artifact generator
182    * @param packageInfoDao               the package info dao
183    * @param activityLogManager           the activity log manager
184    * @param deploymentFlavorDao          the deployment flavor dao
185    * @param nicDao                       the nic dao
186    */
187   public VendorSoftwareProductManagerImpl(
188       VersioningManager versioningManager,
189       VendorSoftwareProductDao vendorSoftwareProductDao,
190       OrchestrationTemplateDao orchestrationTemplateDataDao,
191       VendorSoftwareProductInfoDao vspInfoDao,
192       VendorLicenseFacade vendorLicenseFacade,
193       ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao,
194       EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao,
195       HealingManager healingManager,
196       VendorLicenseArtifactsService licenseArtifactsService,
197       InformationArtifactGenerator informationArtifactGenerator,
198       PackageInfoDao packageInfoDao,
199       ActivityLogManager activityLogManager,
200       DeploymentFlavorDao deploymentFlavorDao,
201       NicDao nicDao,
202       ManualVspToscaManager manualVspToscaManager) {
203     this.versioningManager = versioningManager;
204     this.vendorSoftwareProductDao = vendorSoftwareProductDao;
205     this.orchestrationTemplateDao = orchestrationTemplateDataDao;
206     this.vspInfoDao = vspInfoDao;
207     this.vendorLicenseFacade = vendorLicenseFacade;
208     this.serviceModelDao = serviceModelDao;
209     this.enrichedServiceModelDao = enrichedServiceModelDao;
210     this.healingManager = healingManager;
211     this.licenseArtifactsService = licenseArtifactsService;
212     this.informationArtifactGenerator = informationArtifactGenerator;
213     this.packageInfoDao = packageInfoDao;
214     this.activityLogManager = activityLogManager;
215     this.deploymentFlavorDao = deploymentFlavorDao;
216     this.nicDao = nicDao;
217     this.manualVspToscaManager = manualVspToscaManager;
218
219     registerToVersioning();
220   }
221
222   private void registerToVersioning() {
223     vendorSoftwareProductDao.registerVersioning(
224         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
225     serviceModelDao.registerVersioning(
226         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
227     enrichedServiceModelDao.registerVersioning(
228         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
229   }
230
231   @Override
232   public Version checkout(String vendorSoftwareProductId, String user) {
233     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
234     MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkout_Entity.toString());
235
236     Version newVersion = versioningManager
237         .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
238             vendorSoftwareProductId, user);
239
240     if (newVersion != null) {
241       ActivityLogEntity activityLogEntity =
242           new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1),
243               ActivityType.CHECKOUT.toString(), user, true, "", "");
244       activityLogManager.addActionLog(activityLogEntity, user);
245     }
246
247     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
248     return newVersion;
249   }
250
251
252   @Override
253   public Version undoCheckout(String vendorSoftwareProductId, String user) {
254     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
255
256     Version version =
257         getVersionInfo(vendorSoftwareProductId, VersionableEntityAction.Read, user)
258             .getActiveVersion();
259     String preVspName = vspInfoDao
260         .get(new VspDetails(vendorSoftwareProductId, version)).getName();
261
262     Version newVersion = versioningManager.undoCheckout(
263         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
264         vendorSoftwareProductId, user);
265
266     String postVspName = vspInfoDao
267         .get(new VspDetails(vendorSoftwareProductId, newVersion))
268         .getName();
269
270     updateUniqueName(preVspName, postVspName);
271
272     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
273
274     return newVersion;
275   }
276
277   @Override
278   public Version checkin(String vendorSoftwareProductId, String user) {
279     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
280
281     Version newVersion = versioningManager.checkin(
282         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
283         vendorSoftwareProductId, user, null);
284
285     if (newVersion != null) {
286       ActivityLogEntity activityLogEntity =
287           new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1),
288               ActivityType.CHECKIN.toString(), user, true, "", "");
289       activityLogManager.addActionLog(activityLogEntity, user);
290     }
291
292     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
293
294     return newVersion;
295   }
296
297   @Override
298   public ValidationResponse submit(String vspId, String user) throws IOException {
299     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
300
301     Version version = getVersionInfo(vspId, VersionableEntityAction.Read, user).getActiveVersion();
302     VspDetails vspDetails = getVsp(vspId, version, user);
303     UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version);
304     ToscaServiceModel serviceModel =
305         serviceModelDao.getServiceModel(vspId, vspDetails.getVersion());
306
307     ValidationResponse validationResponse = new ValidationResponse();
308     validationResponse
309         .setVspErrors(validateCompletedVendorSoftwareProduct(vspDetails, uploadData, serviceModel),
310             LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP);
311
312     if (isCyclicDependencyInComponents(vspId, vspDetails.getVersion())) {
313       Collection<ErrorCode> vspErrors = validationResponse.getVspErrors() == null
314           ? new ArrayList<>()
315           : validationResponse.getVspErrors();
316       vspErrors.add(ComponentDependencyModelErrorBuilder
317           .getcyclicDependencyComponentErrorBuilder());
318       validationResponse.setVspErrors(vspErrors, LoggerServiceName.Submit_VSP,
319           LoggerTragetServiceName.SUBMIT_VSP);
320     }
321
322     validationResponse.setLicensingDataErrors(validateLicensingData(vspDetails));
323     validationResponse
324         .setUploadDataErrors(validateUploadData(uploadData, vspDetails),
325             LoggerServiceName.Submit_VSP,
326             LoggerTragetServiceName.SUBMIT_VSP);
327
328     validationResponse.setQuestionnaireValidationResult(
329         validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion(), vspDetails
330             .getOnboardingMethod()));
331
332     if (vspDetails.getOnboardingMethod().equals("Manual")) {
333       Collection<ErrorCode> deploymentFlavourValidationErrList =
334           deploymentFlavorValidation(vspDetails.getId(), vspDetails.getVersion());
335       if (validationResponse.getVspErrors() != null) {
336         if (deploymentFlavourValidationErrList != null) {
337           validationResponse.getVspErrors().addAll(deploymentFlavourValidationErrList);
338         }
339       } else {
340         validationResponse
341             .setVspErrors(deploymentFlavourValidationErrList, LoggerServiceName.Submit_VSP,
342                 LoggerTragetServiceName.SUBMIT_VSP);
343       }
344
345       Set<CompositionEntityValidationData> compositionEntityValidationData =
346           componentValidation(vspDetails.getId(), vspDetails.getVersion());
347       if (validationResponse.getQuestionnaireValidationResult() != null) {
348         if (!CollectionUtils.isEmpty(compositionEntityValidationData)) {
349           validationResponse.getQuestionnaireValidationResult().getValidationData()
350               .addAll(compositionEntityValidationData);
351         }
352       } else {
353         validationResponse.setQuestionnaireValidationResult(
354             CollectionUtils.isEmpty(compositionEntityValidationData) ? null :
355                 new QuestionnaireValidationResult(compositionEntityValidationData));
356       }
357
358       //Generate Tosca service model for Manual Onboarding flow
359       VspModelInfo vspModelInfo = manualVspToscaManager.gatherVspInformation(vspId, version, user);
360       serviceModel = manualVspToscaManager.generateToscaModel(vspModelInfo);
361     }
362     validationResponse.setCompilationErrors(
363         compile(vspId, vspDetails.getVersion(), serviceModel),
364         LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP);
365
366     if (validationResponse.isValid()) {
367       Version newVersion = versioningManager.submit(
368           VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
369           vspId, user, null);
370       ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String
371           .valueOf(newVersion.getMajor()),
372           ActivityType.SUBMIT.toString(), user, true, "", "");
373       activityLogManager.addActionLog(activityLogEntity, user);
374     }
375
376     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
377     return validationResponse;
378   }
379
380   private boolean isCyclicDependencyInComponents(String vendorSoftwareProductId,
381                                                  Version version) {
382     final Collection<ComponentDependencyModelEntity> componentDependencyModelEntities =
383         vendorSoftwareProductDao.listComponentDependencies(vendorSoftwareProductId, version);
384     ComponentDependencyTracker dependencyTracker = new ComponentDependencyTracker();
385
386     for (ComponentDependencyModelEntity entity : componentDependencyModelEntities) {
387       dependencyTracker.addDependency(entity.getSourceComponentId(), entity.getTargetComponentId());
388     }
389     return dependencyTracker.isCyclicDependencyPresent();
390   }
391
392   private Collection<ErrorCode> deploymentFlavorValidation(String vspId,
393                                                            Version version) {
394     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
395     Set<CompositionEntityValidationData> validationData = new HashSet<>();
396     Collection<ErrorCode> errorCodeList = new ArrayList<>();
397     Collection<DeploymentFlavorEntity> deploymentFlavors =
398         vendorSoftwareProductDao.listDeploymentFlavors(vspId, version);
399     if (!CollectionUtils.isEmpty(deploymentFlavors)) {
400       deploymentFlavors.forEach(deploymentFlavor -> {
401         DeploymentFlavorEntity deployment = vendorSoftwareProductDao.getDeploymentFlavor(vspId,
402             version, deploymentFlavor.getId());
403         DeploymentFlavor deploymentlocalFlavor = deployment.getDeploymentFlavorCompositionData();
404         if (deploymentlocalFlavor != null) {
405           if (deploymentlocalFlavor.getFeatureGroupId() == null) {
406             ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder.
407                 getFeatureGroupMandatoryErrorBuilder(deploymentlocalFlavor.getModel());
408             errorCodeList.add(deploymentFlavorErrorBuilder);
409           }
410           List<ComponentComputeAssociation> componetComputeAssociations = new ArrayList<>();
411           componetComputeAssociations = deploymentlocalFlavor.getComponentComputeAssociations();
412           if (CollectionUtils.isEmpty(componetComputeAssociations)) {
413             CompositionEntityValidationData compositionEntityValidationData = new
414                 CompositionEntityValidationData(CompositionEntityType.deployment, deploymentFlavor
415                 .getId());
416             compositionEntityValidationData.setEntityName(deployment
417                 .getDeploymentFlavorCompositionData().getModel());
418             ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder
419                 .getInvalidComponentComputeAssociationErrorBuilder(
420                     deploymentlocalFlavor.getModel());
421
422             errorCodeList.add(deploymentFlavorErrorBuilder);
423           } else {
424             componetComputeAssociations.forEach(componetComputeAssociation -> {
425               if (componetComputeAssociation == null
426                   || !(componetComputeAssociation.getComponentId() != null
427                   && componetComputeAssociation.getComputeFlavorId() != null)) {
428                 CompositionEntityValidationData compositionEntityValidationData = new
429                     CompositionEntityValidationData(CompositionEntityType.deployment,
430                     deploymentFlavor.getId());
431                 compositionEntityValidationData.setEntityName(deployment
432                     .getDeploymentFlavorCompositionData().getModel());
433                 ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder
434                     .getInvalidComponentComputeAssociationErrorBuilder(
435                         deploymentlocalFlavor.getModel());
436
437                 errorCodeList.add(deploymentFlavorErrorBuilder);
438               }
439             });
440           }
441         }
442       });
443     }
444     return errorCodeList;
445   }
446
447   private Set<CompositionEntityValidationData> componentValidation(String vspId, Version version) {
448     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
449
450     Set<CompositionEntityValidationData> validationData = new HashSet<>();
451     Collection<ComponentEntity> components =
452         vendorSoftwareProductDao.listComponents(vspId, version);
453     if (!CollectionUtils.isEmpty(components)) {
454       components.forEach(component -> {
455         validateImage(vspId, version, validationData, component);
456         validateNic(vspId, version, validationData, component);
457
458       });
459     }
460
461     return validationData;
462   }
463
464   private void validateNic(String vspId, Version version,
465                            Set<CompositionEntityValidationData> validationData,
466                            ComponentEntity component) {
467     Collection<NicEntity> nics =
468         nicDao.list(new NicEntity(vspId, version, component.getId(), null));
469     if (CollectionUtils.isNotEmpty(nics)) {
470       nics.forEach(nicEntity -> {
471         NicEntity nic = nicDao.get(new NicEntity(vspId, version, component.getId(),
472             nicEntity.getId()));
473         NetworkType networkType = nic.getNicCompositionData().getNetworkType();
474         String networkId = nic.getNicCompositionData().getNetworkId();
475         if (networkType.equals(NetworkType.Internal) && networkId == null) {
476           CompositionEntityValidationData compositionEntityValidationData = new
477               CompositionEntityValidationData(CompositionEntityType.nic, nic.getId());
478           compositionEntityValidationData.setEntityName(nic.getNicCompositionData().getName());
479           ErrorCode nicInternalNetworkErrorBuilder = NicInternalNetworkErrorBuilder
480               .getNicNullNetworkIdInternalNetworkIdErrorBuilder();
481           List<String> errors = new ArrayList<>();
482           errors.add(nicInternalNetworkErrorBuilder.message());
483           compositionEntityValidationData.setErrors(errors);
484           validationData.add(compositionEntityValidationData);
485         }
486       });
487     }
488   }
489
490   private void validateImage(String vspId, Version version,
491                              Set<CompositionEntityValidationData> validationData,
492                              ComponentEntity component) {
493     Collection<ImageEntity> images = vendorSoftwareProductDao.listImages(vspId, version,
494         component.getId());
495     if (CollectionUtils.isEmpty(images)) {
496       CompositionEntityValidationData compositionEntityValidationData = new
497           CompositionEntityValidationData(component.getType(), component.getId());
498       compositionEntityValidationData.setEntityName(component.getComponentCompositionData()
499           .getDisplayName());
500       ErrorCode vfcMissingImageErrorBuilder =
501           ComponentErrorBuilder.VfcMissingImageErrorBuilder();
502       List<String> errors = new ArrayList<>();
503       errors.add(vfcMissingImageErrorBuilder.message());
504       compositionEntityValidationData.setErrors(errors);
505       validationData.add(compositionEntityValidationData);
506     }
507   }
508
509
510   private List<ErrorCode> validateCompletedVendorSoftwareProduct(
511       VspDetails vspDetails, UploadDataEntity uploadData, Object serviceModel) {
512
513     List<ErrorCode> errors = new ArrayList<>();
514
515     if (vspDetails.getName() == null) {
516       errors.add(createMissingMandatoryFieldError("name"));
517     }
518     if (vspDetails.getDescription() == null) {
519       errors.add(createMissingMandatoryFieldError("description"));
520     }
521     if (vspDetails.getVendorId() == null) {
522       errors.add(createMissingMandatoryFieldError("vendor Id"));
523     }
524     if (vspDetails.getCategory() == null) {
525       errors.add(createMissingMandatoryFieldError("category"));
526     }
527     if (vspDetails.getSubCategory() == null) {
528       errors.add(createMissingMandatoryFieldError("sub category"));
529     }
530     if (vspDetails.getOnboardingMethod().equals("Manual")) {
531       //Manual Onboarding specific validations
532       Collection<DeploymentFlavorEntity> deploymentFlavorEntities = vendorSoftwareProductDao
533           .listDeploymentFlavors(vspDetails.getId(), vspDetails.getVersion());
534       if (CollectionUtils.isEmpty(deploymentFlavorEntities)) {
535         ErrorCode vspMissingDeploymentFlavorErrorBuilder =
536             VendorSoftwareProductInvalidErrorBuilder.VspMissingDeploymentFlavorErrorBuilder();
537         errors.add(vspMissingDeploymentFlavorErrorBuilder);
538       }
539       errors.addAll(validateMandatoryLicenseFields(vspDetails));
540     } else {
541       //Heat flow specific VSP validations
542       if (uploadData == null || uploadData.getContentData() == null || serviceModel == null) {
543         errors.add(VendorSoftwareProductInvalidErrorBuilder
544             .VendorSoftwareProductMissingServiceModelErrorBuilder(vspDetails.getId(),
545                 vspDetails.getVersion()));
546       }
547       if (vspDetails.getVlmVersion() != null || vspDetails.getLicenseAgreement() != null
548           || vspDetails.getFeatureGroups() != null) {
549         errors.addAll(validateMandatoryLicenseFields(vspDetails));
550       }
551     }
552     return errors.isEmpty() ? null : errors;
553   }
554
555   private List<ErrorCode> validateMandatoryLicenseFields(VspDetails vspDetails) {
556     List<ErrorCode> errors = new ArrayList<>();
557     if (vspDetails.getVlmVersion() == null) {
558       errors.add(createMissingMandatoryFieldError(
559           "licensing version (in the format of: {integer}.{integer})"));
560     }
561     if (vspDetails.getLicenseAgreement() == null) {
562       errors.add(createMissingMandatoryFieldError("license agreement"));
563     }
564     if (CollectionUtils.isEmpty(vspDetails.getFeatureGroups())) {
565       errors.add(createMissingMandatoryFieldError("feature groups"));
566     }
567     return errors;
568   }
569
570   private static ErrorCode createMissingMandatoryFieldError(String fieldName) {
571     return new ValidationErrorBuilder("must be supplied", fieldName).build();
572   }
573
574   String getVspQuestionnaireSchema(SchemaTemplateInput schemaInput) {
575     mdcDataDebugMessage.debugEntryMessage(null);
576     mdcDataDebugMessage.debugExitMessage(null);
577     return SchemaGenerator
578         .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, schemaInput);
579   }
580
581   private static void sortVspListByModificationTimeDescOrder(
582       List<VersionedVendorSoftwareProductInfo> vsps) {
583     vsps.sort((o1, o2) -> o2.getVspDetails().getWritetimeMicroSeconds()
584         .compareTo(o1.getVspDetails().getWritetimeMicroSeconds()));
585   }
586
587
588   private Map<String, List<ErrorMessage>> compile(String vendorSoftwareProductId, Version version,
589                                                   ToscaServiceModel serviceModel) {
590     if (serviceModel == null) {
591       return null;
592     }
593
594     enrichedServiceModelDao.deleteAll(vendorSoftwareProductId, version);
595
596     EnrichmentManager<ToscaServiceModel> enrichmentManager =
597         EnrichmentManagerFactory.getInstance().createInterface();
598     enrichmentManager.init(vendorSoftwareProductId, version);
599     enrichmentManager.setModel(serviceModel);
600     Map<String, List<ErrorMessage>> enrichErrors = enrichmentManager.enrich();
601
602     if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, enrichErrors))) {
603       logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.ENRICHMENT_COMPLETED
604           + vendorSoftwareProductId);
605     } else {
606       enrichErrors.values().forEach(errorList ->
607           auditIfContainsErrors(errorList, vendorSoftwareProductId,
608               AuditMessages.ENRICHMENT_ERROR));
609     }
610
611     enrichedServiceModelDao
612         .storeServiceModel(vendorSoftwareProductId, version, enrichmentManager.getModel());
613
614     return enrichErrors;
615   }
616
617   private Collection<ErrorCode> validateLicensingData(VspDetails vspDetails) {
618     mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId());
619
620     if (vspDetails.getVendorId() == null || vspDetails.getVlmVersion() == null
621         || vspDetails.getLicenseAgreement() == null
622         || CollectionUtils.isEmpty(vspDetails.getFeatureGroups())) {
623       return null;
624     }
625
626     mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId());
627     return vendorLicenseFacade
628         .validateLicensingData(vspDetails.getVendorId(), vspDetails.getVlmVersion(),
629             vspDetails.getLicenseAgreement(), vspDetails.getFeatureGroups());
630   }
631
632   @Override
633   public String fetchValidationVsp(String user) {
634     try {
635       validateUniqueName(VALIDATION_VSP_NAME);
636     } catch (Exception ignored) {
637       logger.debug("",ignored);
638       return VALIDATION_VSP_ID;
639     }
640     VspDetails validationVsp = new VspDetails();
641     validationVsp.setName(VALIDATION_VSP_NAME);
642
643     vspInfoDao.create(validationVsp);
644     Version version = versioningManager.create(
645         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
646         validationVsp.getId(), user);
647     validationVsp.setVersion(version);
648
649     createUniqueName(VALIDATION_VSP_NAME);
650     VALIDATION_VSP_ID = validationVsp.getId();
651     return VALIDATION_VSP_ID;
652   }
653
654   @Override
655   public VspDetails createVsp(VspDetails vspDetails, String user) {
656     mdcDataDebugMessage.debugEntryMessage(null);
657
658     validateUniqueName(vspDetails.getName());
659
660     vspDetails.setOnboardingOrigin(OnboardingTypesEnum.NONE.toString());
661
662     vspInfoDao.create(vspDetails);//id will be set in the dao
663     vspInfoDao.updateQuestionnaireData(vspDetails.getId(), null,
664         new JsonSchemaDataGenerator(getVspQuestionnaireSchema(null)).generateData());
665
666     Version version = versioningManager
667         .create(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
668             vspDetails.getId(), user);
669     vspDetails.setVersion(version);
670     ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String
671         .valueOf(vspDetails.getVersion().getMajor() + 1),
672         ActivityType.CREATE_NEW.toString(), user, true, "", "");
673     activityLogManager.addActionLog(activityLogEntity, user);
674     String vspName = vspDetails.getName();
675     createUniqueName(vspName);
676     mdcDataDebugMessage.debugExitMessage(null);
677     return vspDetails;
678   }
679
680   @Override
681   public List<VersionedVendorSoftwareProductInfo> listVsps(String versionFilter, String user) {
682     mdcDataDebugMessage.debugEntryMessage(null);
683
684     Map<String, VersionInfo> idToVersionsInfo = versioningManager.listEntitiesVersionInfo(
685         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, user,
686         VersionableEntityAction.Read);
687
688     List<VersionedVendorSoftwareProductInfo> vsps = new ArrayList<>();
689     for (Map.Entry<String, VersionInfo> entry : idToVersionsInfo.entrySet()) {
690       VersionInfo versionInfo = entry.getValue();
691       if (versionFilter != null && versionFilter.equals(VersionStatus.Final.name())) {
692         if (versionInfo.getLatestFinalVersion() == null) {
693           continue;
694         }
695         versionInfo.setActiveVersion(versionInfo.getLatestFinalVersion());
696         versionInfo.setStatus(VersionStatus.Final);
697         versionInfo.setLockingUser(null);
698       }
699
700       Version version = versionInfo.getActiveVersion();
701       if (user.equals(versionInfo.getLockingUser())) {
702         version.setStatus(VersionStatus.Locked);
703       }
704       try {
705         VspDetails vsp = vspInfoDao.get(new VspDetails(entry.getKey(), version));
706         if (vsp != null && !vsp.getId().equals(VALIDATION_VSP_ID)) {
707           vsp.setValidationDataStructure(null);
708           vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo));
709         }
710       } catch (RuntimeException rte) {
711         logger.debug("",rte);
712         logger.error(
713             "Error trying to retrieve vsp[" + entry.getKey() + "] version[" + version.toString
714                 () + "] " +
715                 "message:" + rte
716                 .getMessage());
717       }
718     }
719
720     sortVspListByModificationTimeDescOrder(vsps);
721
722     mdcDataDebugMessage.debugExitMessage(null);
723
724     return vsps;
725   }
726
727   @Override
728   public void updateVsp(VspDetails vspDetails, String user) {
729     mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId());
730
731     VspDetails retrieved = vspInfoDao.get(vspDetails);
732     if (!retrieved.getOnboardingMethod().equals(vspDetails.getOnboardingMethod())) {
733       final ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder
734           .getOnboardingUpdateError();
735
736       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
737           LoggerTragetServiceName.UPDATE_VSP, ErrorLevel.ERROR.name(),
738           LoggerErrorCode.DATA_ERROR.getErrorCode(), onboardingMethodUpdateErrorCode.message());
739
740       throw new CoreException(onboardingMethodUpdateErrorCode);
741     }
742
743     //If any existing feature group is removed from VSP which is also associated in DF then
744     //update DF to remove feature group associations.
745     updateDeploymentFlavor(vspDetails, user);
746
747     updateUniqueName(retrieved.getName(), vspDetails.getName());
748     vspDetails.setOldVersion(retrieved.getOldVersion());
749
750     vspInfoDao.update(vspDetails);
751     //vendorSoftwareProductDao.updateVspLatestModificationTime(vspDetails.getId(), activeVersion);
752
753     mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId());
754   }
755
756   private void updateDeploymentFlavor(VspDetails vspDetails, String user) {
757     final List<String> featureGroups = vspDetails.getFeatureGroups();
758     if (featureGroups != null) {
759       final Collection<DeploymentFlavorEntity> deploymentFlavorEntities = deploymentFlavorDao
760           .list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails
761               .getVersion(), null));
762       if (Objects.nonNull(deploymentFlavorEntities)) {
763         deploymentFlavorEntities.forEach(deploymentFlavorEntity -> {
764           final String featureGroupId =
765               deploymentFlavorEntity.getDeploymentFlavorCompositionData().getFeatureGroupId();
766           if (!featureGroups.contains(featureGroupId)) {
767             DeploymentFlavor deploymentFlavorCompositionData =
768                 deploymentFlavorEntity.getDeploymentFlavorCompositionData();
769             deploymentFlavorCompositionData.setFeatureGroupId(null);
770             deploymentFlavorEntity.setDeploymentFlavorCompositionData
771                 (deploymentFlavorCompositionData);
772             vendorSoftwareProductDao.updateDeploymentFlavor(deploymentFlavorEntity);
773           }
774         });
775       }
776     }
777   }
778
779
780   @Override
781   public VspDetails getVsp(String vspId, Version version, String user) {
782     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
783
784     VspDetails vsp = vspInfoDao.get(new VspDetails(vspId, version));
785     if (vsp == null) {
786       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
787           LoggerTragetServiceName.GET_VSP, ErrorLevel.ERROR.name(),
788           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Requested VSP not found");
789       throw new CoreException(new VendorSoftwareProductNotFoundErrorBuilder(vspId).build());
790     }
791     vsp.setValidationData(orchestrationTemplateDao.getValidationData(vspId, version));
792
793     if (Objects.isNull(vsp.getOnboardingOrigin())) {
794       vsp.setOnboardingOrigin(OnboardingTypesEnum.ZIP.toString());
795     }
796
797     if (Objects.isNull(vsp.getNetworkPackageName())) {
798       vsp.setNetworkPackageName("Upload File");
799     }
800
801     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
802     return vsp;
803   }
804
805   @Override
806   public Version callAutoHeal(String vspId, VersionInfo versionInfo,
807                               VspDetails vendorSoftwareProductInfo, String user)
808       throws Exception {
809     switch (versionInfo.getStatus()) {
810       case Locked:
811         if (user.equals(versionInfo.getLockingUser())) {
812           autoHeal(vspId, versionInfo.getActiveVersion(), vendorSoftwareProductInfo,
813               versionInfo.getLockingUser());
814         }
815         return versionInfo.getActiveVersion();
816       case Available:
817         Version checkoutVersion = checkout(vspId, user);
818         autoHeal(vspId, checkoutVersion, vendorSoftwareProductInfo, user);
819         return checkin(vspId, user);
820       case Final:
821         Version checkoutFinalVersion = checkout(vspId, user);
822         autoHeal(vspId, checkoutFinalVersion, vendorSoftwareProductInfo, user);
823         Version checkinFinalVersion = checkin(vspId, user);
824         ValidationResponse response = submit(vspId, user);
825         if (!response.isValid()) {
826           return checkout(vspId, user);
827         }
828
829         try {
830           Version finalVersion = checkinFinalVersion.calculateNextFinal();
831           createPackage(vspId, finalVersion, user);
832           return finalVersion;
833         } catch (IOException ex) {
834           logger.debug("",ex);
835           throw new Exception(ex.getMessage());
836         }
837       default:
838         //do nothing
839         break;
840     }
841     return versionInfo.getActiveVersion();
842   }
843
844   @Override
845
846   public void deleteVsp(String vspId, String user) {
847     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
848
849     MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
850         LoggerTragetServiceName.DELETE_VSP, ErrorLevel.ERROR.name(),
851         LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Unsupported operation");
852     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
853
854     throw new UnsupportedOperationException(
855         VendorSoftwareProductConstants.UNSUPPORTED_OPERATION_ERROR);
856   }
857
858   @Override
859   public void heal(String vspId, Version version, String user) {
860     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
861
862     VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user);
863
864     version = VersionStatus.Locked.equals(versionInfo.getStatus())
865         ? versionInfo.getActiveVersion()
866         : checkout(vspId, user);
867     version.setStatus(VersionStatus.Locked);
868
869     Optional<String> errorMessages =
870         healingManager.healAll(getHealingParamsAsMap(vspId, version, user));
871
872     VspDetails vspDetails = new VspDetails(vspId, version);
873     vspDetails.setOldVersion(null);
874     vspInfoDao.updateOldVersionIndication(vspDetails);
875
876     logger.audit("Healed VSP " + vspDetails.getId());
877     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
878
879     if (errorMessages.isPresent()) {
880       throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR")
881           .withCategory(ErrorCategory.APPLICATION).withMessage(errorMessages.get()).build());
882     }
883   }
884
885   private void autoHeal(String vspId, Version checkoutVersion, VspDetails vspDetails, String user) {
886     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
887
888     checkoutVersion.setStatus(VersionStatus.Locked);
889     Map<String, Object> healingParams = getHealingParamsAsMap(vspId, checkoutVersion, user);
890
891     Optional<String> errorMessages = healingManager.healAll(healingParams);
892
893     vspDetails.setVersion(checkoutVersion);
894     vspDetails.setOldVersion(null);
895     vspInfoDao.updateOldVersionIndication(vspDetails);
896
897     logger.audit("Healed VSP " + vspDetails.getName());
898     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
899
900     if (errorMessages.isPresent()) {
901       throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR")
902           .withCategory(ErrorCategory.APPLICATION).withMessage(errorMessages.get()).build());
903     }
904   }
905
906   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) {
907     Map<String, Object> healingParams = new HashMap<>();
908
909     healingParams.put(SdcCommon.VSP_ID, vspId);
910     healingParams.put(SdcCommon.VERSION, version);
911     healingParams.put(SdcCommon.USER, user);
912
913     return healingParams;
914   }
915
916   @Override
917   public List<PackageInfo> listPackages(String category, String subCategory) {
918     return packageInfoDao.listByCategory(category, subCategory);
919   }
920
921   @Override
922   public File getTranslatedFile(String vspId, Version version, String user) {
923     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
924     String errorMessage;
925     if (version == null) {
926       errorMessage = "Package not found";
927       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
928           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
929           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
930       throw new CoreException(new PackageNotFoundErrorBuilder(vspId).build());
931     } else if (!version.isFinal()) {
932       errorMessage = "Invalid requested version";
933       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
934           LoggerTragetServiceName.GET_VERSION_INFO, ErrorLevel.ERROR.name(),
935           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
936       throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
937     }
938
939     PackageInfo packageInfo =
940         packageInfoDao.get(new PackageInfo(vspId, version));
941     if (packageInfo == null) {
942       errorMessage = "Package not found";
943       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
944           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
945           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
946       throw new CoreException(new PackageNotFoundErrorBuilder(vspId, version).build());
947     }
948
949     ByteBuffer translatedFileBuffer = packageInfo.getTranslatedFile();
950     if (translatedFileBuffer == null) {
951       errorMessage = "Package not found";
952       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
953           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
954           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
955       throw new CoreException(new PackageInvalidErrorBuilder(vspId, version).build());
956     }
957
958     File translatedFile = new File(VendorSoftwareProductConstants.VSP_PACKAGE_ZIP);
959
960     try {
961       FileOutputStream fos = new FileOutputStream(translatedFile);
962       fos.write(translatedFileBuffer.array());
963       fos.close();
964     } catch (IOException exception) {
965       errorMessage = "Can't create package";
966       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
967           LoggerTragetServiceName.CREATE_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
968           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
969       throw new CoreException(new TranslationFileCreationErrorBuilder(vspId, version).build(),
970           exception);
971     }
972
973     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
974
975     return translatedFile;
976   }
977
978   @Override
979
980   public byte[] getOrchestrationTemplateFile(String vspId, Version version, String user) {
981     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
982
983     UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version);
984     ByteBuffer contentData = uploadData.getContentData();
985     if (contentData == null) {
986       return null;
987     }
988
989     ByteArrayOutputStream baos = new ByteArrayOutputStream();
990
991     try (final ZipOutputStream zos = new ZipOutputStream(baos);
992          ZipInputStream zipStream = new ZipInputStream(
993              new ByteArrayInputStream(contentData.array()))) {
994       zos.write(contentData.array());
995     } catch (IOException exception) {
996       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
997           LoggerTragetServiceName.GET_UPLOADED_HEAT, ErrorLevel.ERROR.name(),
998           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't get uploaded HEAT");
999       throw new CoreException(new FileCreationErrorBuilder(vspId).build(), exception);
1000     }
1001
1002     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1003     return baos.toByteArray();
1004   }
1005
1006   @Override
1007   public PackageInfo createPackage(String vspId, Version version, String user) throws IOException {
1008     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
1009
1010     if (!version.isFinal()) {
1011       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
1012           LoggerTragetServiceName.CREATE_PACKAGE, ErrorLevel.ERROR.name(),
1013           LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't create package");
1014       throw new CoreException(
1015           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
1016               .build());
1017     }
1018
1019     ToscaServiceModel toscaServiceModel = enrichedServiceModelDao.getServiceModel(vspId, version);
1020     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
1021     Version vlmVersion = vspDetails.getVlmVersion();
1022
1023     PackageInfo packageInfo = createPackageInfo(vspId, vspDetails);
1024
1025     ToscaFileOutputServiceCsarImpl toscaServiceTemplateServiceCsar =
1026         new ToscaFileOutputServiceCsarImpl();
1027     FileContentHandler licenseArtifacts = licenseArtifactsService
1028         .createLicenseArtifacts(vspDetails.getId(), vspDetails.getVendorId(), vlmVersion,
1029             vspDetails.getFeatureGroups(), user);
1030     //todo add tosca validation here
1031     packageInfo.setTranslatedFile(ByteBuffer.wrap(
1032         toscaServiceTemplateServiceCsar.createOutputFile(toscaServiceModel, licenseArtifacts)));
1033
1034     packageInfoDao.create(packageInfo);
1035
1036     logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_PACKAGE + vspId);
1037
1038     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1039     return packageInfo;
1040   }
1041
1042   private PackageInfo createPackageInfo(String vspId, VspDetails vspDetails) {
1043     PackageInfo packageInfo = new PackageInfo();
1044     packageInfo.setVspId(vspId);
1045     packageInfo.setVersion(vspDetails.getVersion());
1046     packageInfo.setVspName(vspDetails.getName());
1047     packageInfo.setVspDescription(vspDetails.getDescription());
1048     packageInfo.setCategory(vspDetails.getCategory());
1049     packageInfo.setSubCategory(vspDetails.getSubCategory());
1050     packageInfo.setVendorName(vspDetails.getVendorName());
1051     packageInfo.setPackageType(VendorSoftwareProductConstants.CSAR);
1052     packageInfo.setVendorRelease("1.0"); //todo TBD
1053     return packageInfo;
1054   }
1055
1056   @Override
1057
1058   public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version, String user) {
1059     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
1060
1061     VspQuestionnaireEntity retrieved = vspInfoDao.getQuestionnaire(vspId, version);
1062     VersioningUtil.validateEntityExistence(retrieved, new VspQuestionnaireEntity(vspId, version),
1063         VspDetails.ENTITY_TYPE);
1064
1065     String questionnaireData = retrieved.getQuestionnaireData();
1066
1067     QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse();
1068     questionnaireResponse.setData(questionnaireData);
1069     questionnaireResponse.setSchema(getVspQuestionnaireSchema(null));
1070
1071     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1072
1073     return questionnaireResponse;
1074   }
1075
1076   @Override
1077   public void updateVspQuestionnaire(String vspId, Version version, String questionnaireData,
1078                                      String user) {
1079     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
1080
1081     vspInfoDao.updateQuestionnaireData(vspId, version, questionnaireData);
1082
1083     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1084   }
1085
1086
1087   private Map<String, List<ErrorMessage>> validateUploadData(UploadDataEntity uploadData,
1088                                                              VspDetails vspDetails)
1089       throws IOException {
1090
1091     Map<String, List<ErrorMessage>> validationErrors = new HashMap<>();
1092     if (uploadData == null || uploadData.getContentData() == null) {
1093       return null;
1094     }
1095
1096     FileContentHandler fileContentMap =
1097         CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.getOnboardingTypesEnum
1098                 (vspDetails.getOnboardingOrigin()),
1099             uploadData.getContentData().array());
1100
1101     if (vspDetails.getOnboardingOrigin().equals(OnboardingTypesEnum.ZIP.name().toLowerCase())) {
1102       ValidationManager validationManager =
1103           ValidationManagerUtil.initValidationManager(fileContentMap);
1104       validationErrors.putAll(validationManager.validate());
1105     }
1106
1107     return
1108         MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, validationErrors))
1109             ? null : validationErrors;
1110   }
1111
1112   private VersionInfo getVersionInfo(String vendorSoftwareProductId, VersionableEntityAction action,
1113                                      String user) {
1114     return versioningManager.getEntityVersionInfo(
1115         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
1116         vendorSoftwareProductId, user, action);
1117   }
1118
1119
1120   private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version,
1121                                                               String onboardingMethod) {
1122     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
1123
1124     // The apis of CompositionEntityDataManager used here are stateful!
1125     // so, it must be re-created from scratch when it is used!
1126     CompositionEntityDataManager compositionEntityDataManager =
1127         CompositionEntityDataManagerFactory.getInstance().createInterface();
1128     compositionEntityDataManager
1129         .addEntity(vspInfoDao.getQuestionnaire(vspId, version), null);
1130
1131     Collection<NicEntity> nics = vendorSoftwareProductDao.listNicsByVsp(vspId, version);
1132
1133     Map<String, List<String>> nicNamesByComponent = new HashMap<>();
1134     for (NicEntity nicEntity : nics) {
1135       compositionEntityDataManager.addEntity(nicEntity, null);
1136
1137       Nic nic = nicEntity.getNicCompositionData();
1138       if (nic != null && nic.getName() != null) {
1139         List<String> nicNames =
1140             nicNamesByComponent.computeIfAbsent(nicEntity.getComponentId(), k -> new ArrayList<>());
1141         nicNames.add(nic.getName());
1142       }
1143     }
1144
1145     Collection<ComponentEntity> components =
1146         vendorSoftwareProductDao.listComponentsCompositionAndQuestionnaire(vspId, version);
1147     components.forEach(component -> compositionEntityDataManager.addEntity(component,
1148         new ComponentQuestionnaireSchemaInput(nicNamesByComponent.get(component.getId()),
1149             JsonUtil.json2Object(component.getQuestionnaireData(), Map.class))));
1150
1151     Collection<ComputeEntity> computes = vendorSoftwareProductDao.listComputesByVsp(vspId, version);
1152     computes.forEach(compute -> compositionEntityDataManager.addEntity(compute, null));
1153
1154     if ("Manual".equals(onboardingMethod)) {
1155       Collection<ImageEntity> images = vendorSoftwareProductDao.listImagesByVsp(vspId, version);
1156       images.forEach(image -> compositionEntityDataManager.addEntity(image, null));
1157     }
1158
1159     Map<CompositionEntityId, Collection<String>> errorsByEntityId =
1160         compositionEntityDataManager.validateEntitiesQuestionnaire();
1161     if (MapUtils.isNotEmpty(errorsByEntityId)) {
1162       compositionEntityDataManager.buildTrees();
1163       compositionEntityDataManager.addErrorsToTrees(errorsByEntityId);
1164 /*      Set<CompositionEntityValidationData> entitiesWithValidationErrors =
1165           compositionEntityDataManager.getEntityListWithErrors();*/
1166       //Collection<CompositionEntityValidationData> roots = compositionEntityDataManager.getTrees();
1167
1168       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1169       return new QuestionnaireValidationResult(
1170           compositionEntityDataManager.getAllErrorsByVsp(vspId));
1171     }
1172
1173     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1174     return null;
1175   }
1176
1177   @Override
1178   public File getInformationArtifact(String vspId, Version version, String user) {
1179     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
1180     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
1181
1182     if (vspDetails == null) {
1183       return null;
1184     }
1185
1186     String vspName = vspDetails.getName();
1187     ByteBuffer infoArtifactAsByteBuffer;
1188     File infoArtifactFile;
1189     try {
1190       infoArtifactAsByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate(vspId,
1191           version).getBytes());
1192
1193       infoArtifactFile =
1194           new File(
1195               String.format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName));
1196       OutputStream out = new BufferedOutputStream(new FileOutputStream(infoArtifactFile));
1197       out.write(infoArtifactAsByteBuffer.array());
1198       out.close();
1199     } catch (IOException ex) {
1200       throw new CoreException(new InformationArtifactCreationErrorBuilder(vspId).build(), ex);
1201     }
1202
1203     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
1204     return infoArtifactFile;
1205   }
1206
1207   void validateUniqueName(String vspName) {
1208     UniqueValueUtil.validateUniqueValue(
1209         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName);
1210   }
1211
1212   void createUniqueName(String vspName) {
1213     UniqueValueUtil.createUniqueValue(
1214         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName);
1215   }
1216
1217   void updateUniqueName(String oldVspName, String newVspName) {
1218     UniqueValueUtil.updateUniqueValue(
1219         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME,
1220         oldVspName, newVspName);
1221   }
1222
1223   @Override
1224   public Collection<ComputeEntity> getComputeByVsp(String vspId, Version version,
1225                                                    String user) {
1226     return vendorSoftwareProductDao.listComputesByVsp(vspId, version);
1227   }
1228
1229   private void auditIfContainsErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
1230
1231     errorList.forEach(errorMessage -> {
1232       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
1233         logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(),
1234             vspId));
1235       }
1236     });
1237   }
1238 }