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