[SDC-29] Amdocs OnBoard 1707 initial commit.
[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.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.healing.api.HealingManager;
46 import org.openecomp.sdc.logging.api.Logger;
47 import org.openecomp.sdc.logging.api.LoggerFactory;
48 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
49 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
50 import org.openecomp.sdc.logging.types.LoggerConstants;
51 import org.openecomp.sdc.logging.types.LoggerErrorCode;
52 import org.openecomp.sdc.logging.types.LoggerServiceName;
53 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
54 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
55 import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl;
56 import org.openecomp.sdc.validation.util.ValidationManagerUtil;
57 import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
58 import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService;
59 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
60 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
61 import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao;
62 import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao;
63 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao;
64 import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao;
65 import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.VendorSoftwareProductNotFoundErrorBuilder;
66 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity;
67 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity;
68 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
70 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity;
73 import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelErrorBuilder;
74 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
75 import org.openecomp.sdc.vendorsoftwareproduct.errors.FileCreationErrorBuilder;
76 import org.openecomp.sdc.vendorsoftwareproduct.errors.InformationArtifactCreationErrorBuilder;
77 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageInvalidErrorBuilder;
78 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
79 import org.openecomp.sdc.vendorsoftwareproduct.errors.TranslationFileCreationErrorBuilder;
80 import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductInvalidErrorBuilder;
81 import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator;
82 import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager;
83 import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGenerator;
84 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
85 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireValidationResult;
86 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
87 import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo;
88 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId;
89 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType;
90 import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic;
91 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComponentQuestionnaireSchemaInput;
92 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext;
93 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput;
94 import org.openecomp.sdc.vendorsoftwareproduct.utils.ComponentDependencyTracker;
95 import org.openecomp.sdc.versioning.VersioningManager;
96 import org.openecomp.sdc.versioning.VersioningUtil;
97 import org.openecomp.sdc.versioning.dao.types.Version;
98 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
99 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
100 import org.openecomp.sdc.versioning.types.VersionInfo;
101 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
102 import org.openecomp.sdcrests.activitylog.types.ActivityType;
103 import org.slf4j.MDC;
104
105 import java.io.BufferedOutputStream;
106 import java.io.ByteArrayInputStream;
107 import java.io.ByteArrayOutputStream;
108 import java.io.File;
109 import java.io.FileOutputStream;
110 import java.io.IOException;
111 import java.io.OutputStream;
112 import java.nio.ByteBuffer;
113 import java.util.ArrayList;
114 import java.util.Collection;
115 import java.util.HashMap;
116 import java.util.List;
117 import java.util.Map;
118 import java.util.zip.ZipInputStream;
119 import java.util.zip.ZipOutputStream;
120
121 public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductManager {
122   private static final String VALIDATION_VSP_ID = "validationOnlyVspId";
123   private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
124   //private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
125
126   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
127   private static final Logger logger =
128       LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class);
129
130   private OrchestrationTemplateDao orchestrationTemplateDao;
131   private VendorSoftwareProductInfoDao vspInfoDao;
132   private VersioningManager versioningManager;
133   private VendorSoftwareProductDao vendorSoftwareProductDao;
134   private VendorLicenseFacade vendorLicenseFacade;
135   private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao;
136   private EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao;
137   private HealingManager healingManager;
138   private VendorLicenseArtifactsService licenseArtifactsService;
139   private CompositionEntityDataManager compositionEntityDataManager;
140   private InformationArtifactGenerator informationArtifactGenerator;
141   private PackageInfoDao packageInfoDao;
142   private ActivityLogManager activityLogManager;
143
144
145   public VendorSoftwareProductManagerImpl(
146       VersioningManager versioningManager,
147       VendorSoftwareProductDao vendorSoftwareProductDao,
148       OrchestrationTemplateDao orchestrationTemplateDataDao,
149       VendorSoftwareProductInfoDao vspInfoDao,
150       VendorLicenseFacade vendorLicenseFacade,
151       ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao,
152       EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao,
153       HealingManager healingManager,
154       VendorLicenseArtifactsService licenseArtifactsService,
155       CompositionEntityDataManager compositionEntityDataManager,
156       InformationArtifactGenerator informationArtifactGenerator,
157       PackageInfoDao packageInfoDao,
158       ActivityLogManager activityLogManager) {
159     this.versioningManager = versioningManager;
160     this.vendorSoftwareProductDao = vendorSoftwareProductDao;
161     this.orchestrationTemplateDao = orchestrationTemplateDataDao;
162     this.vspInfoDao = vspInfoDao;
163     this.vendorLicenseFacade = vendorLicenseFacade;
164     this.serviceModelDao = serviceModelDao;
165     this.enrichedServiceModelDao = enrichedServiceModelDao;
166     this.healingManager = healingManager;
167     this.licenseArtifactsService = licenseArtifactsService;
168     this.compositionEntityDataManager = compositionEntityDataManager;
169     this.informationArtifactGenerator = informationArtifactGenerator;
170     this.packageInfoDao = packageInfoDao;
171     this.activityLogManager = activityLogManager;
172
173     registerToVersioning();
174   }
175
176   private void registerToVersioning() {
177     vendorSoftwareProductDao.registerVersioning(
178         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
179     serviceModelDao.registerVersioning(
180         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
181     enrichedServiceModelDao.registerVersioning(
182         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
183   }
184
185   @Override
186   public Version checkout(String vendorSoftwareProductId, String user) {
187     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
188     MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkout_Entity.toString());
189
190     Version newVersion = versioningManager
191         .checkout(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
192             vendorSoftwareProductId, user);
193
194     if (newVersion != null) {
195       ActivityLogEntity activityLogEntity =
196           new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1),
197               ActivityType.CHECKOUT.toString(), user, true, "", "");
198       activityLogManager.addActionLog(activityLogEntity, user);
199     }
200
201     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
202     return newVersion;
203   }
204
205
206   @Override
207   public Version undoCheckout(String vendorSoftwareProductId, String user) {
208     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
209
210     Version version =
211         getVersionInfo(vendorSoftwareProductId, VersionableEntityAction.Read, user)
212             .getActiveVersion();
213     String preVspName = vspInfoDao
214         .get(new VspDetails(vendorSoftwareProductId, version)).getName();
215
216     Version newVersion = versioningManager.undoCheckout(
217         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
218         vendorSoftwareProductId, user);
219
220     String postVspName = vspInfoDao
221         .get(new VspDetails(vendorSoftwareProductId, newVersion))
222         .getName();
223
224     updateUniqueName(preVspName, postVspName);
225
226     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
227
228     return newVersion;
229   }
230
231   @Override
232   public Version checkin(String vendorSoftwareProductId, String user) {
233     mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId);
234
235     Version newVersion = versioningManager.checkin(
236         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
237         vendorSoftwareProductId, user, null);
238
239     if (newVersion != null) {
240       ActivityLogEntity activityLogEntity =
241           new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(newVersion.getMajor() + 1),
242               ActivityType.CHECKIN.toString(), user, true, "", "");
243       activityLogManager.addActionLog(activityLogEntity, user);
244     }
245
246     mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId);
247
248     return newVersion;
249   }
250
251   @Override
252   public ValidationResponse submit(String vspId, String user) throws IOException {
253     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
254
255     Version version = getVersionInfo(vspId, VersionableEntityAction.Read, user).getActiveVersion();
256     VspDetails vspDetails = getVsp(vspId, version, user);
257     UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version);
258     ToscaServiceModel serviceModel =
259         serviceModelDao.getServiceModel(vspId, vspDetails.getVersion());
260
261     ValidationResponse validationResponse = new ValidationResponse();
262     validationResponse
263         .setVspErrors(validateCompletedVendorSoftwareProduct(vspDetails, uploadData, serviceModel),
264             LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP);
265
266     if (isCyclicDependencyInComponents(vspId, vspDetails.getVersion())) {
267       Collection<ErrorCode> vspErrors = validationResponse.getVspErrors() == null
268           ? new ArrayList<>()
269           : validationResponse.getVspErrors();
270       vspErrors.add(ComponentDependencyModelErrorBuilder
271           .getcyclicDependencyComponentErrorBuilder());
272       validationResponse.setVspErrors(vspErrors, LoggerServiceName.Submit_VSP,
273           LoggerTragetServiceName.SUBMIT_VSP);
274     }
275
276     validationResponse.setLicensingDataErrors(validateLicensingData(vspDetails));
277     validationResponse
278         .setUploadDataErrors(validateUploadData(uploadData), LoggerServiceName.Submit_VSP,
279             LoggerTragetServiceName.SUBMIT_VSP);
280     validationResponse.setQuestionnaireValidationResult(
281         validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion()));
282
283     validationResponse.setCompilationErrors(
284         compile(vspId, vspDetails.getVersion(), serviceModel),
285         LoggerServiceName.Submit_VSP, LoggerTragetServiceName.SUBMIT_VSP);
286
287     if (validationResponse.isValid()) {
288       Version newVersion = versioningManager.submit(
289           VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
290           vspId, user, null);
291       ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String
292           .valueOf(newVersion.getMajor()),
293           ActivityType.SUBMIT.toString(), user, true, "", "");
294       activityLogManager.addActionLog(activityLogEntity, user);
295     }
296
297     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
298
299     return validationResponse;
300   }
301
302   private boolean isCyclicDependencyInComponents(String vendorSoftwareProductId,
303                                                  Version version) {
304     final Collection<ComponentDependencyModelEntity> componentDependencyModelEntities =
305         vendorSoftwareProductDao.listComponentDependencies(vendorSoftwareProductId, version);
306     ComponentDependencyTracker dependencyTracker = new ComponentDependencyTracker();
307
308     for (ComponentDependencyModelEntity entity : componentDependencyModelEntities) {
309       dependencyTracker.addDependency(entity.getSourceComponentId(), entity.getTargetComponentId());
310     }
311     return dependencyTracker.isCyclicDependencyPresent();
312   }
313
314   private static List<ErrorCode> validateCompletedVendorSoftwareProduct(
315       VspDetails vspDetails, UploadDataEntity uploadData, Object serviceModel) {
316
317     List<ErrorCode> errros = new ArrayList<>();
318
319     if (vspDetails.getName() == null) {
320       errros.add(createMissingMandatoryFieldError("name"));
321     }
322     if (vspDetails.getDescription() == null) {
323       errros.add(createMissingMandatoryFieldError("description"));
324     }
325     if (vspDetails.getVendorId() == null) {
326       errros.add(createMissingMandatoryFieldError("vendor Id"));
327     }
328     if (vspDetails.getVlmVersion() == null) {
329       errros.add(createMissingMandatoryFieldError(
330           "licensing version (in the format of: {integer}.{integer})"));
331     }
332     if (vspDetails.getCategory() == null) {
333       errros.add(createMissingMandatoryFieldError("category"));
334     }
335     if (vspDetails.getSubCategory() == null) {
336       errros.add(createMissingMandatoryFieldError("sub category"));
337     }
338     if (vspDetails.getLicenseAgreement() == null) {
339       errros.add(createMissingMandatoryFieldError("license agreement"));
340     }
341     if (CollectionUtils.isEmpty(vspDetails.getFeatureGroups())) {
342       errros.add(createMissingMandatoryFieldError("feature groups"));
343     }
344     if (uploadData == null || uploadData.getContentData() == null || serviceModel == null) {
345       errros.add(
346           new VendorSoftwareProductInvalidErrorBuilder(vspDetails.getId(), vspDetails.getVersion())
347               .build());
348     }
349
350     return errros.isEmpty() ? null : errros;
351   }
352
353   private static ErrorCode createMissingMandatoryFieldError(String fieldName) {
354     return new ValidationErrorBuilder("must be supplied", fieldName).build();
355   }
356
357   String getVspQuestionnaireSchema(SchemaTemplateInput schemaInput) {
358     mdcDataDebugMessage.debugEntryMessage(null);
359     mdcDataDebugMessage.debugExitMessage(null);
360     return SchemaGenerator
361         .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, schemaInput);
362   }
363
364   private static void sortVspListByModificationTimeDescOrder(
365       List<VersionedVendorSoftwareProductInfo> vsps) {
366     vsps.sort((o1, o2) -> o2.getVspDetails().getWritetimeMicroSeconds()
367         .compareTo(o1.getVspDetails().getWritetimeMicroSeconds()));
368   }
369
370
371   private Map<String, List<ErrorMessage>> compile(String vendorSoftwareProductId, Version version,
372                                                   ToscaServiceModel serviceModel) {
373     if (serviceModel == null) {
374       return null;
375     }
376
377     enrichedServiceModelDao.deleteAll(vendorSoftwareProductId, version);
378
379     EnrichmentManager<ToscaServiceModel> enrichmentManager =
380         EnrichmentManagerFactory.getInstance().createInterface();
381     enrichmentManager.init(vendorSoftwareProductId, version);
382     enrichmentManager.setModel(serviceModel);
383     Map<String, List<ErrorMessage>> enrichErrors = enrichmentManager.enrich();
384
385     enrichedServiceModelDao
386         .storeServiceModel(vendorSoftwareProductId, version, enrichmentManager.getModel());
387
388     return enrichErrors;
389   }
390
391   private Collection<ErrorCode> validateLicensingData(VspDetails vspDetails) {
392     mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId());
393
394     if (vspDetails.getVendorId() == null || vspDetails.getVlmVersion() == null
395         || vspDetails.getLicenseAgreement() == null
396         || CollectionUtils.isEmpty(vspDetails.getFeatureGroups())) {
397       return null;
398     }
399
400     mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId());
401     return vendorLicenseFacade
402         .validateLicensingData(vspDetails.getVendorId(), vspDetails.getVlmVersion(),
403             vspDetails.getLicenseAgreement(), vspDetails.getFeatureGroups());
404   }
405
406   @Override
407   public String fetchValidationVsp(String user) {
408     try {
409       validateUniqueName(VALIDATION_VSP_NAME);
410     } catch (Exception ignored) {
411       return VALIDATION_VSP_ID;
412     }
413     VspDetails validationVsp = new VspDetails();
414     validationVsp.setName(VALIDATION_VSP_NAME);
415     validationVsp.setId(VALIDATION_VSP_ID);
416     Version version = versioningManager.create(
417         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
418         validationVsp.getId(),
419         user);
420     validationVsp.setVersion(version);
421
422     vspInfoDao.create(validationVsp);
423     createUniqueName(VALIDATION_VSP_NAME);
424     return VALIDATION_VSP_ID;
425   }
426
427   @Override
428   public VspDetails createVsp(VspDetails vspDetails, String user) {
429     mdcDataDebugMessage.debugEntryMessage(null);
430
431     validateUniqueName(vspDetails.getName());
432
433     vspInfoDao.create(vspDetails);//id will be set in the dao
434     vspInfoDao.updateQuestionnaireData(vspDetails.getId(), null,
435         new JsonSchemaDataGenerator(getVspQuestionnaireSchema(null)).generateData());
436
437     Version version = versioningManager
438         .create(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
439             vspDetails.getId(), user);
440     vspDetails.setVersion(version);
441     ActivityLogEntity activityLogEntity = new ActivityLogEntity(vspDetails.getId(), String
442         .valueOf(vspDetails.getVersion().getMajor() + 1),
443         ActivityType.CREATE_NEW.toString(), user, true, "", "");
444     activityLogManager.addActionLog(activityLogEntity, user);
445     String vspName = vspDetails.getName();
446     createUniqueName(vspName);
447     mdcDataDebugMessage.debugExitMessage(null);
448     return vspDetails;
449   }
450
451   @Override
452   public List<VersionedVendorSoftwareProductInfo> listVsps(String versionFilter, String user) {
453     mdcDataDebugMessage.debugEntryMessage(null);
454
455     Map<String, VersionInfo> idToVersionsInfo = versioningManager.listEntitiesVersionInfo(
456         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, user,
457         VersionableEntityAction.Read);
458
459     List<VersionedVendorSoftwareProductInfo> vsps = new ArrayList<>();
460     for (Map.Entry<String, VersionInfo> entry : idToVersionsInfo.entrySet()) {
461       VersionInfo versionInfo = entry.getValue();
462       if (versionFilter != null && versionFilter.equals(VersionStatus.Final.name())) {
463         if (versionInfo.getLatestFinalVersion() == null) {
464           continue;
465         }
466         versionInfo.setActiveVersion(versionInfo.getLatestFinalVersion());
467         versionInfo.setStatus(VersionStatus.Final);
468         versionInfo.setLockingUser(null);
469       }
470
471       Version version = versionInfo.getActiveVersion();
472       if (user.equals(versionInfo.getLockingUser())) {
473         version.setStatus(VersionStatus.Locked);
474       }
475       VspDetails vsp = vspInfoDao.get(new VspDetails(entry.getKey(), version));
476       if (vsp != null && !vsp.getId().equals(VALIDATION_VSP_ID)) {
477         vsp.setValidationDataStructure(null);
478         vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo));
479       }
480     }
481
482     sortVspListByModificationTimeDescOrder(vsps);
483
484     mdcDataDebugMessage.debugExitMessage(null);
485
486     return vsps;
487   }
488
489   @Override
490   public void updateVsp(VspDetails vspDetails, String user) {
491     mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId());
492
493     VspDetails retrieved = vspInfoDao.get(vspDetails);
494
495     updateUniqueName(retrieved.getName(), vspDetails.getName());
496     vspDetails.setOldVersion(retrieved.getOldVersion());
497
498     vspInfoDao.update(vspDetails);
499     //vendorSoftwareProductDao.updateVspLatestModificationTime(vspDetails.getId(), activeVersion);
500
501     mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId());
502   }
503
504
505   @Override
506   public VspDetails getVsp(String vspId, Version version, String user) {
507     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
508
509     VspDetails vsp = vspInfoDao.get(new VspDetails(vspId, version));
510     if (vsp == null) {
511       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
512           LoggerTragetServiceName.GET_VSP, ErrorLevel.ERROR.name(),
513           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Requested VSP not found");
514       throw new CoreException(new VendorSoftwareProductNotFoundErrorBuilder(vspId).build());
515     }
516     vsp.setValidationData(orchestrationTemplateDao.getValidationData(vspId, version));
517
518     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
519     return vsp;
520   }
521
522   @Override
523   public Version callAutoHeal(String vspId, VersionInfo versionInfo,
524                               VspDetails vendorSoftwareProductInfo, String user)
525       throws Exception {
526     switch (versionInfo.getStatus()) {
527       case Locked:
528         if (user.equals(versionInfo.getLockingUser())) {
529           autoHeal(vspId, versionInfo.getActiveVersion(), vendorSoftwareProductInfo,
530               versionInfo.getLockingUser());
531         }
532         return versionInfo.getActiveVersion();
533       case Available:
534         Version checkoutVersion = checkout(vspId, user);
535         autoHeal(vspId, checkoutVersion, vendorSoftwareProductInfo, user);
536         return checkin(vspId, user);
537       case Final:
538         Version checkoutFinalVersion = checkout(vspId,user);
539         autoHeal(vspId, checkoutFinalVersion, vendorSoftwareProductInfo, user);
540         Version checkinFinalVersion = checkin(vspId,user);
541         ValidationResponse response = submit(vspId, user);
542         if(!response.isValid()) {
543           return checkout(vspId, user);
544         }
545
546         try {
547           Version finalVersion = checkinFinalVersion.calculateNextFinal();
548           createPackage(vspId, finalVersion, user);
549           return finalVersion;
550         } catch (IOException e) {
551           throw new Exception(e.getMessage());
552         }
553     }
554     return versionInfo.getActiveVersion();
555   }
556
557   @Override
558
559   public void deleteVsp(String vspId, String user) {
560     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
561
562     MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
563         LoggerTragetServiceName.DELETE_VSP, ErrorLevel.ERROR.name(),
564         LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Unsupported operation");
565     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
566
567     throw new UnsupportedOperationException(
568         VendorSoftwareProductConstants.UNSUPPORTED_OPERATION_ERROR);
569   }
570
571   @Override
572   public void heal(String vspId, Version version, String user) {
573     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
574
575     VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user);
576
577     version = VersionStatus.Locked.equals(versionInfo.getStatus())
578         ? versionInfo.getActiveVersion()
579         : checkout(vspId, user);
580     version.setStatus(VersionStatus.Locked);
581
582     healingManager.healAll(getHealingParamsAsMap(vspId, version, user));
583
584     VspDetails vspDetails = new VspDetails(vspId, version);
585     vspDetails.setOldVersion(null);
586     vspInfoDao.updateOldVersionIndication(vspDetails);
587
588     logger.audit("Healed VSP " + vspDetails.getId());
589     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
590   }
591
592   private void autoHeal(String vspId, Version checkoutVersion, VspDetails vspDetails, String user) {
593     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
594
595     checkoutVersion.setStatus(VersionStatus.Locked);
596     Map<String, Object> healingParams = getHealingParamsAsMap(vspId, checkoutVersion, user);
597     healingManager.healAll(healingParams);
598     vspDetails.setVersion(checkoutVersion);
599     vspDetails.setOldVersion(null);
600     vspInfoDao.updateOldVersionIndication(vspDetails);
601
602     logger.audit("Healed VSP " + vspDetails.getName());
603
604     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
605   }
606
607   private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) {
608     Map<String, Object> healingParams = new HashMap<>();
609
610     healingParams.put(SdcCommon.VSP_ID, vspId);
611     healingParams.put(SdcCommon.VERSION, version);
612     healingParams.put(SdcCommon.USER, user);
613
614     return healingParams;
615   }
616
617   @Override
618   public List<PackageInfo> listPackages(String category, String subCategory) {
619     return packageInfoDao.listByCategory(category, subCategory);
620   }
621
622   @Override
623   public File getTranslatedFile(String vspId, Version version, String user) {
624     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
625     String errorMessage;
626     if (version == null) {
627       errorMessage = "Package not found";
628       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
629           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
630           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
631       throw new CoreException(new PackageNotFoundErrorBuilder(vspId).build());
632     } else if (!version.isFinal()) {
633       errorMessage = "Invalid requested version";
634       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
635           LoggerTragetServiceName.GET_VERSION_INFO, ErrorLevel.ERROR.name(),
636           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
637       throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
638     }
639
640     PackageInfo packageInfo =
641         packageInfoDao.get(new PackageInfo(vspId, version));
642     if (packageInfo == null) {
643       errorMessage = "Package not found";
644       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
645           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
646           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
647       throw new CoreException(new PackageNotFoundErrorBuilder(vspId, version).build());
648     }
649
650     ByteBuffer translatedFileBuffer = packageInfo.getTranslatedFile();
651     if (translatedFileBuffer == null) {
652       errorMessage = "Package not found";
653       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
654           LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
655           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
656       throw new CoreException(new PackageInvalidErrorBuilder(vspId, version).build());
657     }
658
659     File translatedFile = new File(VendorSoftwareProductConstants.VSP_PACKAGE_ZIP);
660
661     try {
662       FileOutputStream fos = new FileOutputStream(translatedFile);
663       fos.write(translatedFileBuffer.array());
664       fos.close();
665     } catch (IOException exception) {
666       errorMessage = "Can't create package";
667       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
668           LoggerTragetServiceName.CREATE_TRANSLATED_FILE, ErrorLevel.ERROR.name(),
669           LoggerErrorCode.DATA_ERROR.getErrorCode(), errorMessage);
670       throw new CoreException(new TranslationFileCreationErrorBuilder(vspId, version).build(),
671           exception);
672     }
673
674     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
675
676     return translatedFile;
677   }
678
679   @Override
680
681   public byte[] getOrchestrationTemplateFile(String vspId, Version version, String user) {
682     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
683
684     UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version);
685     ByteBuffer contentData = uploadData.getContentData();
686     if (contentData == null) {
687       return null;
688     }
689
690     ByteArrayOutputStream baos = new ByteArrayOutputStream();
691
692     try (final ZipOutputStream zos = new ZipOutputStream(baos);
693          ZipInputStream zipStream = new ZipInputStream(
694              new ByteArrayInputStream(contentData.array()))) {
695       zos.write(contentData.array());
696     } catch (IOException exception) {
697       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
698           LoggerTragetServiceName.GET_UPLOADED_HEAT, ErrorLevel.ERROR.name(),
699           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't get uploaded HEAT");
700       throw new CoreException(new FileCreationErrorBuilder(vspId).build(), exception);
701     }
702
703     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
704     return baos.toByteArray();
705   }
706
707   @Override
708   public PackageInfo createPackage(String vspId, Version version, String user) throws IOException {
709     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
710
711     if (!version.isFinal()) {
712       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
713           LoggerTragetServiceName.CREATE_PACKAGE, ErrorLevel.ERROR.name(),
714           LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't create package");
715       throw new CoreException(
716           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
717               .build());
718     }
719
720     ToscaServiceModel toscaServiceModel = enrichedServiceModelDao.getServiceModel(vspId, version);
721     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
722     Version vlmVersion = vspDetails.getVlmVersion();
723
724     PackageInfo packageInfo = createPackageInfo(vspId, vspDetails);
725
726     ToscaFileOutputServiceCsarImpl toscaServiceTemplateServiceCsar =
727         new ToscaFileOutputServiceCsarImpl();
728     FileContentHandler licenseArtifacts = licenseArtifactsService
729         .createLicenseArtifacts(vspDetails.getId(), vspDetails.getVendorId(), vlmVersion,
730             vspDetails.getFeatureGroups(), user);
731     //todo add tosca validation here
732     packageInfo.setTranslatedFile(ByteBuffer.wrap(
733         toscaServiceTemplateServiceCsar.createOutputFile(toscaServiceModel, licenseArtifacts)));
734
735     packageInfoDao.create(packageInfo);
736
737     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
738     return packageInfo;
739   }
740
741   private PackageInfo createPackageInfo(String vspId, VspDetails vspDetails) {
742     PackageInfo packageInfo = new PackageInfo();
743     packageInfo.setVspId(vspId);
744     packageInfo.setVersion(vspDetails.getVersion());
745     packageInfo.setVspName(vspDetails.getName());
746     packageInfo.setVspDescription(vspDetails.getDescription());
747     packageInfo.setCategory(vspDetails.getCategory());
748     packageInfo.setSubCategory(vspDetails.getSubCategory());
749     packageInfo.setVendorName(vspDetails.getVendorName());
750     packageInfo.setPackageType(VendorSoftwareProductConstants.CSAR);
751     packageInfo.setVendorRelease("1.0"); //todo TBD
752     return packageInfo;
753   }
754
755   @Override
756
757   public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version, String user) {
758     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
759
760     VspQuestionnaireEntity retrieved = vspInfoDao.getQuestionnaire(vspId, version);
761     VersioningUtil.validateEntityExistence(retrieved, new VspQuestionnaireEntity(vspId, version),
762         VspDetails.ENTITY_TYPE);
763
764     String questionnaireData = retrieved.getQuestionnaireData();
765
766     QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse();
767     questionnaireResponse.setData(questionnaireData);
768     questionnaireResponse.setSchema(getVspQuestionnaireSchema(null));
769
770     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
771
772     return questionnaireResponse;
773   }
774
775   @Override
776   public void updateVspQuestionnaire(String vspId, Version version, String questionnaireData,
777                                      String user) {
778     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
779
780     vspInfoDao.updateQuestionnaireData(vspId, version, questionnaireData);
781
782     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
783   }
784
785
786   private Map<String, List<ErrorMessage>> validateUploadData(UploadDataEntity uploadData)
787       throws IOException {
788     if (uploadData == null || uploadData.getContentData() == null) {
789       return null;
790     }
791
792     FileContentHandler fileContentMap =
793         CommonUtil.loadUploadFileContent(uploadData.getContentData().array());
794     //todo - check
795     ValidationManager validationManager =
796         ValidationManagerUtil.initValidationManager(fileContentMap);
797     Map<String, List<ErrorMessage>> validationErrors = validationManager.validate();
798
799     return
800         MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, validationErrors))
801             ? null : validationErrors;
802   }
803
804   private VersionInfo getVersionInfo(String vendorSoftwareProductId, VersionableEntityAction action,
805                                      String user) {
806     return versioningManager.getEntityVersionInfo(
807         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE,
808         vendorSoftwareProductId, user, action);
809   }
810
811
812   private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version) {
813     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
814
815
816     compositionEntityDataManager
817         .addEntity(vspInfoDao.getQuestionnaire(vspId, version), null);
818
819     Collection<NicEntity> nics = vendorSoftwareProductDao.listNicsByVsp(vspId, version);
820
821     Map<String, List<String>> nicNamesByComponent = new HashMap<>();
822     for (NicEntity nicEntity : nics) {
823       compositionEntityDataManager.addEntity(nicEntity, null);
824
825       Nic nic = nicEntity.getNicCompositionData();
826       if (nic != null && nic.getName() != null) {
827         List<String> nicNames =
828             nicNamesByComponent.computeIfAbsent(nicEntity.getComponentId(), k -> new ArrayList<>());
829         nicNames.add(nic.getName());
830       }
831     }
832
833     Collection<ComponentEntity> components =
834         vendorSoftwareProductDao.listComponentsCompositionAndQuestionnaire(vspId, version);
835     components.forEach(component -> compositionEntityDataManager.addEntity(component,
836         new ComponentQuestionnaireSchemaInput(nicNamesByComponent.get(component.getId()),
837             JsonUtil.json2Object(component.getQuestionnaireData(), Map.class))));
838
839     Map<CompositionEntityId, Collection<String>> errorsByEntityId =
840         compositionEntityDataManager.validateEntitiesQuestionnaire();
841     if (MapUtils.isNotEmpty(errorsByEntityId)) {
842       compositionEntityDataManager.buildTrees();
843       compositionEntityDataManager.addErrorsToTrees(errorsByEntityId);
844 /*      Set<CompositionEntityValidationData> entitiesWithValidationErrors =
845           compositionEntityDataManager.getEntityListWithErrors();*/
846       //Collection<CompositionEntityValidationData> roots = compositionEntityDataManager.getTrees();
847
848       mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
849       return new QuestionnaireValidationResult(
850           compositionEntityDataManager.getAllErrorsByVsp(vspId));
851     }
852
853     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
854     return null;
855   }
856
857   @Override
858   public File getInformationArtifact(String vspId, Version version, String user) {
859     mdcDataDebugMessage.debugEntryMessage("VSP id", vspId);
860     VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version));
861
862     if (vspDetails == null) {
863       return null;
864     }
865
866     String vspName = vspDetails.getName();
867     ByteBuffer infoArtifactAsByteBuffer;
868     File infoArtifactFile;
869     try {
870       infoArtifactAsByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate(vspId,
871           version).getBytes());
872
873       infoArtifactFile =
874           new File(
875               String.format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName));
876       OutputStream out = new BufferedOutputStream(new FileOutputStream(infoArtifactFile));
877       out.write(infoArtifactAsByteBuffer.array());
878       out.close();
879     } catch (IOException e) {
880       throw new CoreException(new InformationArtifactCreationErrorBuilder(vspId).build(), e);
881     }
882
883     mdcDataDebugMessage.debugExitMessage("VSP id", vspId);
884     return infoArtifactFile;
885   }
886
887   void validateUniqueName(String vspName) {
888     UniqueValueUtil.validateUniqueValue(
889         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName);
890   }
891
892   void createUniqueName(String vspName) {
893     UniqueValueUtil.createUniqueValue(
894         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, vspName);
895   }
896
897   void updateUniqueName(String oldVspName, String newVspName) {
898     UniqueValueUtil.updateUniqueValue(
899         VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME,
900         oldVspName, newVspName);
901   }
902 }