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