6431db3354ca4bfc61a08a8756d7fc387877eb79
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.openecomp.sdcrests.vsp.rest.services;
17
18 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
19 import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
20 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
21 import static org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod.NetworkPackage;
22 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
23 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
24 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
25 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
26 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.util.Collection;
31 import java.util.Comparator;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Objects;
37 import java.util.Optional;
38 import java.util.function.Predicate;
39 import java.util.stream.Collectors;
40 import javax.inject.Named;
41 import javax.ws.rs.core.Response;
42 import org.apache.commons.collections4.MapUtils;
43 import org.openecomp.core.dao.UniqueValueDaoFactory;
44 import org.openecomp.core.util.UniqueValueUtil;
45 import org.openecomp.sdc.activitylog.ActivityLogManager;
46 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
47 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
48 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
49 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
50 import org.openecomp.sdc.be.csar.storage.StorageFactory;
51 import org.openecomp.sdc.common.errors.CoreException;
52 import org.openecomp.sdc.common.errors.ErrorCode;
53 import org.openecomp.sdc.common.errors.Messages;
54 import org.openecomp.sdc.datatypes.error.ErrorMessage;
55 import org.openecomp.sdc.datatypes.model.ItemType;
56 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
57 import org.openecomp.sdc.itempermissions.PermissionsManager;
58 import org.openecomp.sdc.itempermissions.PermissionsManagerFactory;
59 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
60 import org.openecomp.sdc.logging.api.Logger;
61 import org.openecomp.sdc.logging.api.LoggerFactory;
62 import org.openecomp.sdc.notification.dtos.Event;
63 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
64 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
65 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
66 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
67 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
68 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
70 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
73 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
74 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
75 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
76 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
77 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
79 import org.openecomp.sdc.versioning.AsdcItemManager;
80 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
81 import org.openecomp.sdc.versioning.VersioningManager;
82 import org.openecomp.sdc.versioning.VersioningManagerFactory;
83 import org.openecomp.sdc.versioning.dao.types.Version;
84 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
85 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
86 import org.openecomp.sdc.versioning.types.Item;
87 import org.openecomp.sdc.versioning.types.ItemStatus;
88 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
89 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
90 import org.openecomp.sdcrests.item.types.ItemCreationDto;
91 import org.openecomp.sdcrests.item.types.VersionDto;
92 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
93 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
94 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
95 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
96 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
97 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
98 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
99 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
100 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
101 import org.openecomp.sdcrests.vsp.rest.CatalogVspClient;
102 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
103 import org.openecomp.sdcrests.vsp.rest.exception.VendorSoftwareProductsExceptionSupplier;
104 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
105 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
106 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
107 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
108 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
109 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
110 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
111 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
112 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
113 import org.springframework.context.annotation.Scope;
114 import org.springframework.stereotype.Service;
115
116 @Named
117 @Service("vendorSoftwareProducts")
118 @Scope(value = "prototype")
119 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
120
121     private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
122     private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
123     private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
124     private static final String ATTACHMENT_FILENAME = "attachment; filename=";
125     private static final String SUBMIT_HEALED_VERSION_ERROR = "VSP Id %s: Error while submitting version %s created based on Certified version %s for healing purpose.";
126     private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
127     private static final Object VALIDATION_VSP_CACHE_LOCK = new Object();
128     private static ItemCreationDto cachedValidationVsp;
129     private final AsdcItemManager itemManager;
130     private final PermissionsManager permissionsManager;
131     private final VersioningManager versioningManager;
132     private final VendorSoftwareProductManager vendorSoftwareProductManager;
133     private final ActivityLogManager activityLogManager;
134     private final NotificationPropagationManager notifier;
135     private final UniqueValueUtil uniqueValueUtil;
136     private final StorageFactory storageFactory;
137     private final CatalogVspClient catalogVspClient;
138
139     public VendorSoftwareProductsImpl() {
140         this.itemManager = AsdcItemManagerFactory.getInstance().createInterface();
141         this.permissionsManager = PermissionsManagerFactory.getInstance().createInterface();
142         this.versioningManager = VersioningManagerFactory.getInstance().createInterface();
143         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
144         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
145         this.notifier = NotificationPropagationManagerFactory.getInstance().createInterface();
146         this.uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface());
147         this.storageFactory = new StorageFactory();
148         this.catalogVspClient = new CatalogVspClientImpl();
149     }
150
151     public VendorSoftwareProductsImpl(AsdcItemManager itemManager,
152                                       PermissionsManager permissionsManager,
153                                       VersioningManager versioningManager,
154                                       VendorSoftwareProductManager vendorSoftwareProductManager,
155                                       ActivityLogManager activityLogManager,
156                                       NotificationPropagationManager notifier,
157                                       UniqueValueUtil uniqueValueUtil,
158                                       final StorageFactory storageFactory,
159                                       CatalogVspClient catalogVspClient) {
160         this.itemManager = itemManager;
161         this.permissionsManager = permissionsManager;
162         this.versioningManager = versioningManager;
163         this.vendorSoftwareProductManager = vendorSoftwareProductManager;
164         this.activityLogManager = activityLogManager;
165         this.notifier = notifier;
166         this.uniqueValueUtil = uniqueValueUtil;
167         this.storageFactory = storageFactory;
168         this.catalogVspClient = catalogVspClient;
169     }
170
171     @Override
172     public Response createVsp(VspRequestDto vspRequestDto, String user) {
173         ItemCreationDto vspCreationDto = createVspItem(vspRequestDto, user);
174         return Response.ok(vspCreationDto).build();
175     }
176
177     private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) {
178         OnboardingMethod onboardingMethod = null;
179         try {
180             onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
181         } catch (IllegalArgumentException e) {
182             LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
183             throwUnknownOnboardingMethodException(e);
184         }
185         ItemCreationDto itemCreationDto = null;
186         if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) {
187             itemCreationDto = createItem(vspRequestDto, user, onboardingMethod);
188         } else {
189             throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
190         }
191         return itemCreationDto;
192     }
193
194     private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) {
195         Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
196         item.setType(ItemType.vsp.name());
197         item.setOwner(user);
198         item.setStatus(ItemStatus.ACTIVE);
199         item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
200         uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
201         item = itemManager.create(item);
202         uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
203         Version version = versioningManager.create(item.getId(), new Version(), null);
204         VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
205         vspDetails.setId(item.getId());
206         vspDetails.setVersion(version);
207         vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
208         vendorSoftwareProductManager.createVsp(vspDetails);
209         versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
210         ItemCreationDto itemCreationDto = new ItemCreationDto();
211         itemCreationDto.setItemId(item.getId());
212         itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
213         activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", ""));
214         return itemCreationDto;
215     }
216
217     private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
218         ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder();
219         throw new CoreException(onboardingMethodUpdateErrorCode, e);
220     }
221
222     @Override
223     public Response listVsps(String versionStatus, String itemStatus, String user) {
224         GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
225         MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
226         getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
227         return Response.ok(results).build();
228     }
229
230     @Override
231     public Response getVsp(String vspId, String versionId, String user) {
232         Version version = versioningManager.get(vspId, new Version(versionId));
233         VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
234         try {
235             HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> {
236                 vspDetails.setVersion(healedVersion);
237                 if (version.getStatus() == VersionStatus.Certified) {
238                     submitHealedVersion(vspDetails, versionId, user);
239                 }
240             });
241         } catch (Exception e) {
242             LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e);
243         }
244         VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
245         addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto);
246         return Response.ok(vspDetailsDto).build();
247     }
248
249     @Override
250     public Response getLatestVsp(final String vspId, final String user) {
251         final List<Version> versions = versioningManager.list(vspId);
252         final Version version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
253             .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
254             .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
255         return getVsp(vspId, version.getId(), user);
256     }
257
258     private void submitHealedVersion(VspDetails vspDetails, String baseVersionId, String user) {
259         try {
260             if (vspDetails.getVlmVersion() != null) {
261                 // sync vlm if not exists on user space
262                 versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
263             }
264             submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> {
265                 throw new IllegalStateException("Certified vsp after healing failed on validation");
266             });
267             vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
268         } catch (Exception ex) {
269             LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex);
270         }
271     }
272
273     @Override
274     public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) {
275         VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
276         vspDetails.setId(vspId);
277         vspDetails.setVersion(new Version(versionId));
278         vendorSoftwareProductManager.updateVsp(vspDetails);
279         updateVspItem(vspId, vspDescriptionDto);
280         return Response.ok().build();
281     }
282
283     @Override
284     public Response deleteVsp(final String vspId, final String user) {
285         final Item vsp = itemManager.get(vspId);
286         if (!ItemType.vsp.getName().equals(vsp.getType())) {
287             throw VendorSoftwareProductsExceptionSupplier.vspNotFound(vspId).get();
288         }
289
290         checkIfCanDeleteVsp(vsp, user);
291
292         try {
293             deleteVspFromStorage(vspId, user);
294         } catch (final Exception e) {
295             logDeleteFromStorageFailure(vspId, user);
296             throw VendorSoftwareProductsExceptionSupplier.deleteVspFromStorageFailure(vspId).get();
297         }
298
299         try {
300             deleteVsp(vspId, user, vsp);
301         } catch (final Exception e) {
302             throw VendorSoftwareProductsExceptionSupplier.deleteVspFromDatabaseFailure(vspId).get();
303         }
304
305         return Response.ok().build();
306     }
307
308     private void checkIfCanDeleteVsp(final Item vsp, final String user) {
309         final String vspId = vsp.getId();
310
311         checkIfVspInUse(user, vspId);
312
313         if (isVspItemNeverCertified(vsp)) {
314             return;
315         }
316         if (!isVspItemArchived(vspId, user)) {
317             throw VendorSoftwareProductsExceptionSupplier.deleteNotArchivedVsp(vspId).get();
318         }
319     }
320
321     private void checkIfVspInUse(final String user, final String vspId) {
322         final Optional<String> vfNameThatUsesVspOpt;
323         try {
324             vfNameThatUsesVspOpt = catalogVspClient.findNameOfVfUsingVsp(vspId, user);
325         } catch (final Exception e) {
326             throw VendorSoftwareProductsExceptionSupplier.deleteGenericError(vspId).get();
327         }
328         if (vfNameThatUsesVspOpt.isPresent()) {
329             final String vfName = vfNameThatUsesVspOpt.get();
330             throw VendorSoftwareProductsExceptionSupplier.vspInUseByVf(vfName).get();
331         }
332     }
333
334     private boolean isVspItemArchived(final String vspId, final String user) {
335         return getVspList(null, ItemStatus.ARCHIVED.name(), user).stream().anyMatch(item -> vspId.equals(item.getId()));
336     }
337
338     private boolean isVspItemNeverCertified(final Item vsp) {
339         final Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
340         return certifiedVersionsCounter == null || certifiedVersionsCounter == 0;
341     }
342
343     private void deleteVspFromStorage(final String vspId, final String user) {
344         final ArtifactStorageManager artifactStorageManager = storageFactory.createArtifactStorageManager();
345         if (artifactStorageManager.isEnabled()) {
346             artifactStorageManager.delete(vspId);
347             logDeleteFromStorageAllSuccess(vspId, user);
348         }
349     }
350
351     private void logDeleteFromStorageFailure(final String vspId, final String user) {
352         final String message = Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId);
353         try {
354             versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
355                 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, false, message, message)
356             ));
357         } catch (final Exception e) {
358             LOGGER.error("Could not log activity '{}'", message, e);
359         }
360     }
361     private void logDeleteFromStorageAllSuccess(final String vspId, final String user) {
362         final String message = String.format("VSP '%s' fully deleted from the storage", vspId);
363         try {
364             versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
365                 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, true, message, message)
366             ));
367         } catch (final Exception e) {
368             LOGGER.error("Could not log activity '{}'", message, e);
369         }
370     }
371
372     private void deleteVsp(final String vspId, final String user, final Item vsp) {
373         versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
374         itemManager.delete(vsp);
375         permissionsManager.deleteItemPermissions(vspId);
376         uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
377         notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
378     }
379
380     @Override
381     public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
382         throws IOException {
383         Version version = new Version(versionId);
384         if (request.getAction() == VendorSoftwareProductAction.Submit) {
385             if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
386                 return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
387             }
388             String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
389             Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
390             if (validationResponse.isPresent()) {
391                 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
392                     .applyMapping(validationResponse.get(), ValidationResponseDto.class);
393                 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
394             }
395             notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
396         } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
397             return createPackage(vspId, version);
398         }
399         return Response.ok().build();
400     }
401
402     @Override
403     public Response getValidationVsp(String user) {
404         ItemCreationDto validationVsp = retrieveValidationVsp();
405         return Response.ok(validationVsp).build();
406     }
407
408     private ItemCreationDto retrieveValidationVsp() {
409         synchronized (VALIDATION_VSP_CACHE_LOCK) {
410             if (cachedValidationVsp != null) {
411                 return cachedValidationVsp;
412             }
413             VspRequestDto validationVspRequest = new VspRequestDto();
414             validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
415             validationVspRequest.setName(VALIDATION_VSP_NAME);
416             try {
417                 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
418                 return cachedValidationVsp;
419             } catch (CoreException vspCreateException) {
420                 LOGGER.debug("Failed to create validation VSP", vspCreateException);
421                 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
422                     .equals(item.getName());
423                 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
424                         "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
425                     .getId();
426                 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
427                 cachedValidationVsp = new ItemCreationDto();
428                 cachedValidationVsp.setItemId(validationVspId);
429                 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
430                 return cachedValidationVsp;
431             }
432         }
433     }
434
435     @Override
436     public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
437         byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
438         if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
439             return Response.status(Response.Status.NOT_FOUND).build();
440         }
441         Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
442         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
443         return response.build();
444     }
445
446     @Override
447     public Response listPackages(String status, String category, String subCategory, String user) {
448         List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
449             .collect(Collectors.toList());
450         List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
451         packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
452         GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
453         MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
454         if (packageInfoList != null) {
455             for (PackageInfo packageInfo : packageInfoList) {
456                 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
457             }
458         }
459         return Response.ok(results).build();
460     }
461
462     @Override
463     public Response getTranslatedFile(String vspId, String versionId, String user) {
464         final List<Version> versions = versioningManager.list(vspId);
465         final Version version;
466         if (versionId == null) {
467             version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
468                 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
469                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
470         } else {
471             version = versions.stream()
472                 .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
473                 .findFirst()
474                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
475             if (version.getStatus() != VersionStatus.Certified) {
476                 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
477             }
478         }
479         File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
480         Response.ResponseBuilder response = Response.ok(zipFile);
481         if (zipFile == null) {
482             return Response.status(Response.Status.NOT_FOUND).build();
483         }
484         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
485         return response.build();
486     }
487
488     @Override
489     public Response getQuestionnaire(String vspId, String versionId, String user) {
490         QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
491         if (questionnaireResponse.getErrorMessage() != null) {
492             return Response.status(Response.Status.EXPECTATION_FAILED)
493                 .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
494                 .build();
495         }
496         QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
497             .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
498         return Response.ok(result).build();
499     }
500
501     @Override
502     public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
503         vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
504         return Response.ok().build();
505     }
506
507     @Override
508     public Response heal(String vspId, String versionId, String user) {
509         HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
510         return Response.ok().build();
511     }
512
513     @Override
514     public Response getVspInformationArtifact(String vspId, String versionId, String user) {
515         File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
516         Response.ResponseBuilder response = Response.ok(textInformationArtifact);
517         if (textInformationArtifact == null) {
518             return Response.status(Response.Status.NOT_FOUND).build();
519         }
520         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
521         return response.build();
522     }
523
524     @Override
525     public Response listComputes(String vspId, String version, String user) {
526         Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
527         MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
528         GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
529         for (ComputeEntity compute : computes) {
530             results.add(mapper.applyMapping(compute, VspComputeDto.class));
531         }
532         return Response.ok(results).build();
533     }
534
535     private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
536         Item retrievedItem = itemManager.get(vspId);
537         Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
538         item.setId(vspId);
539         item.setType(retrievedItem.getType());
540         item.setOwner(retrievedItem.getOwner());
541         item.setStatus(retrievedItem.getStatus());
542         item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
543         item.setCreationTime(retrievedItem.getCreationTime());
544         item.setModificationTime(new Date());
545         item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
546         itemManager.update(item);
547     }
548
549     private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
550         VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
551         if (vspDetails.getVlmVersion() != null) {
552             vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
553         }
554         ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
555         Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
556         if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
557             activityLogManager
558                 .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
559             return Optional.of(validationResponse);
560         }
561         versioningManager.submit(vspId, version, message);
562         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
563         return Optional.empty();
564     }
565
566     private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
567         Map<String, Object> eventProperties = new HashMap<>();
568         eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
569         eventProperties.put(ITEM_ID, itemId);
570         if (version != null) {
571             eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
572             eventProperties.put(VERSION_ID, version.getId());
573         }
574         eventProperties.put(SUBMIT_DESCRIPTION, message);
575         eventProperties.put(PERMISSION_USER, userName);
576         Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
577         try {
578             notifier.notifySubscribers(syncEvent, userName);
579         } catch (Exception e) {
580             LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
581         }
582     }
583
584     private Response createPackage(String vspId, Version version) throws IOException {
585         Version retrievedVersion = versioningManager.get(vspId, version);
586         if (retrievedVersion.getStatus() != VersionStatus.Certified) {
587             throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
588         }
589         PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
590         return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
591     }
592
593     private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
594         Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
595             .getInfo(vspId, version);
596         if (candidateInfo.isPresent()) {
597             if (candidateInfo.get().getValidationDataStructure() != null) {
598                 vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
599             }
600             vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
601             vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
602         } else {
603             OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
604             if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
605                 if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
606                     vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
607                 }
608                 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
609                 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
610             }
611         }
612     }
613
614     private boolean userHasPermission(String itemId, String userId) {
615         return permissionsManager.getUserItemPermission(itemId, userId)
616             .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
617     }
618
619     private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
620         Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
621         if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
622             itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
623         } else {
624             itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
625             if (VersionStatus.Certified.name().equals(versionStatus)) {
626                 itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
627             } else if (VersionStatus.Draft.name().equals(versionStatus)) {
628                 itemPredicate = itemPredicate
629                     .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
630             }
631         }
632         return itemPredicate;
633     }
634
635     private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
636         Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
637         return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
638             .collect(Collectors.toList());
639     }
640
641     private class SyncEvent implements Event {
642
643         private final String eventType;
644         private final String originatorId;
645         private final Map<String, Object> attributes;
646         private final String entityId;
647
648         SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
649             this.eventType = eventType;
650             this.originatorId = originatorId;
651             this.attributes = attributes;
652             this.entityId = entityId;
653         }
654
655         @Override
656         public String getEventType() {
657             return eventType;
658         }
659
660         @Override
661         public String getOriginatorId() {
662             return originatorId;
663         }
664
665         @Override
666         public Map<String, Object> getAttributes() {
667             return attributes;
668         }
669
670         @Override
671         public String getEntityId() {
672             return entityId;
673         }
674     }
675 }