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