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