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