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