9bb68f23afcf0af4fdadad29cb8e47e7b5d0156f
[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.core.validation.errors.ErrorMessagesFormatBuilder;
46 import org.openecomp.sdc.activitylog.ActivityLogManager;
47 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
48 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
49 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
50 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
51 import org.openecomp.sdc.be.csar.storage.StorageFactory;
52 import org.openecomp.sdc.common.errors.CoreException;
53 import org.openecomp.sdc.common.errors.ErrorCode;
54 import org.openecomp.sdc.common.errors.Messages;
55 import org.openecomp.sdc.datatypes.error.ErrorMessage;
56 import org.openecomp.sdc.datatypes.model.ItemType;
57 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
58 import org.openecomp.sdc.itempermissions.PermissionsManager;
59 import org.openecomp.sdc.itempermissions.PermissionsManagerFactory;
60 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
61 import org.openecomp.sdc.logging.api.Logger;
62 import org.openecomp.sdc.logging.api.LoggerFactory;
63 import org.openecomp.sdc.notification.dtos.Event;
64 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
65 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
66 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
67 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
68 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
70 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
73 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
74 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
75 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
76 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
77 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
79 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
80 import org.openecomp.sdc.versioning.AsdcItemManager;
81 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
82 import org.openecomp.sdc.versioning.VersioningManager;
83 import org.openecomp.sdc.versioning.VersioningManagerFactory;
84 import org.openecomp.sdc.versioning.dao.types.Version;
85 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
86 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
87 import org.openecomp.sdc.versioning.types.Item;
88 import org.openecomp.sdc.versioning.types.ItemStatus;
89 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
90 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
91 import org.openecomp.sdcrests.item.types.ItemCreationDto;
92 import org.openecomp.sdcrests.item.types.VersionDto;
93 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
94 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
95 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
96 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
97 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
98 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
99 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
100 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
101 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
102 import org.openecomp.sdcrests.vsp.rest.CatalogVspClient;
103 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
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(String vspId, String user) {
285         Item vsp = itemManager.get(vspId);
286         if (!vsp.getType().equals(ItemType.vsp.name())) {
287             throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vsp with id %s does not exist.", vspId)).build()));
288         }
289         try {
290             Optional<String> optUsedInVf = catalogVspClient.findNameOfVfUsingVsp(vspId, user);
291             if (optUsedInVf.isPresent()) {
292                 return Response.status(Response.Status.FORBIDDEN).entity(
293                         new Exception(ErrorMessagesFormatBuilder.getErrorWithParameters(Messages.DELETE_VSP_ERROR_USED_BY_VF.getErrorMessage(), optUsedInVf.get(), optUsedInVf.get()))
294                 ).build();
295             }
296         } catch (Exception e) {
297             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vsp with id %s cannot be deleted due to error %s.", vspId, e.getMessage())).build()))).build();
298         }
299
300         Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
301         final ArtifactStorageManager artifactStorageManager = storageFactory.createArtifactStorageManager();
302         if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
303             if (artifactStorageManager.isEnabled() && !deleteVspFromStorage(vspId, artifactStorageManager)) {
304                 return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
305                     .entity(new Exception(Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId))).build();
306             }
307             return deleteVsp(vspId, user, vsp);
308         } else {
309             final var isVspArchived = getVspList(null, ItemStatus.ARCHIVED.name(), user).stream().anyMatch(item -> item.getId().equals(vspId));
310             if (isVspArchived) {
311                 if (artifactStorageManager.isEnabled() && !deleteVspFromStorage(vspId, artifactStorageManager)) {
312                     return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
313                         .entity(new Exception(Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId))).build();
314                 }
315                 return deleteVsp(vspId, user, vsp);
316             }
317             return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
318         }
319     }
320
321     private boolean deleteVspFromStorage(final String vspId, final ArtifactStorageManager artifactStorageManager) {
322         try {
323             artifactStorageManager.delete(vspId);
324         } catch (final Exception e) {
325             LOGGER.error("Failed to delete VSP '{}'", vspId, e);
326             return false;
327         }
328         return true;
329     }
330
331     private Response deleteVsp(String vspId, String user, Item vsp) {
332         versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
333         itemManager.delete(vsp);
334         permissionsManager.deleteItemPermissions(vspId);
335         uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
336         notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
337         return Response.ok().build();
338     }
339
340     @Override
341     public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
342         throws IOException {
343         Version version = new Version(versionId);
344         if (request.getAction() == VendorSoftwareProductAction.Submit) {
345             if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
346                 return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
347             }
348             String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
349             Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
350             if (validationResponse.isPresent()) {
351                 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
352                     .applyMapping(validationResponse.get(), ValidationResponseDto.class);
353                 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
354             }
355             notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
356         } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
357             return createPackage(vspId, version);
358         }
359         return Response.ok().build();
360     }
361
362     @Override
363     public Response getValidationVsp(String user) {
364         ItemCreationDto validationVsp = retrieveValidationVsp();
365         return Response.ok(validationVsp).build();
366     }
367
368     private ItemCreationDto retrieveValidationVsp() {
369         synchronized (VALIDATION_VSP_CACHE_LOCK) {
370             if (cachedValidationVsp != null) {
371                 return cachedValidationVsp;
372             }
373             VspRequestDto validationVspRequest = new VspRequestDto();
374             validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
375             validationVspRequest.setName(VALIDATION_VSP_NAME);
376             try {
377                 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
378                 return cachedValidationVsp;
379             } catch (CoreException vspCreateException) {
380                 LOGGER.debug("Failed to create validation VSP", vspCreateException);
381                 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
382                     .equals(item.getName());
383                 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
384                         "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
385                     .getId();
386                 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
387                 cachedValidationVsp = new ItemCreationDto();
388                 cachedValidationVsp.setItemId(validationVspId);
389                 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
390                 return cachedValidationVsp;
391             }
392         }
393     }
394
395     @Override
396     public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
397         byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
398         if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
399             return Response.status(Response.Status.NOT_FOUND).build();
400         }
401         Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
402         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
403         return response.build();
404     }
405
406     @Override
407     public Response listPackages(String status, String category, String subCategory, String user) {
408         List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
409             .collect(Collectors.toList());
410         List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
411         packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
412         GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
413         MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
414         if (packageInfoList != null) {
415             for (PackageInfo packageInfo : packageInfoList) {
416                 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
417             }
418         }
419         return Response.ok(results).build();
420     }
421
422     @Override
423     public Response getTranslatedFile(String vspId, String versionId, String user) {
424         final List<Version> versions = versioningManager.list(vspId);
425         final Version version;
426         if (versionId == null) {
427             version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
428                 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
429                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
430         } else {
431             version = versions.stream()
432                 .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
433                 .findFirst()
434                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
435             if (version.getStatus() != VersionStatus.Certified) {
436                 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
437             }
438         }
439         File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
440         Response.ResponseBuilder response = Response.ok(zipFile);
441         if (zipFile == null) {
442             return Response.status(Response.Status.NOT_FOUND).build();
443         }
444         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
445         return response.build();
446     }
447
448     @Override
449     public Response getQuestionnaire(String vspId, String versionId, String user) {
450         QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
451         if (questionnaireResponse.getErrorMessage() != null) {
452             return Response.status(Response.Status.EXPECTATION_FAILED)
453                 .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
454                 .build();
455         }
456         QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
457             .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
458         return Response.ok(result).build();
459     }
460
461     @Override
462     public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
463         vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
464         return Response.ok().build();
465     }
466
467     @Override
468     public Response heal(String vspId, String versionId, String user) {
469         HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
470         return Response.ok().build();
471     }
472
473     @Override
474     public Response getVspInformationArtifact(String vspId, String versionId, String user) {
475         File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
476         Response.ResponseBuilder response = Response.ok(textInformationArtifact);
477         if (textInformationArtifact == null) {
478             return Response.status(Response.Status.NOT_FOUND).build();
479         }
480         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
481         return response.build();
482     }
483
484     @Override
485     public Response listComputes(String vspId, String version, String user) {
486         Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
487         MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
488         GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
489         for (ComputeEntity compute : computes) {
490             results.add(mapper.applyMapping(compute, VspComputeDto.class));
491         }
492         return Response.ok(results).build();
493     }
494
495     private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
496         Item retrievedItem = itemManager.get(vspId);
497         Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
498         item.setId(vspId);
499         item.setType(retrievedItem.getType());
500         item.setOwner(retrievedItem.getOwner());
501         item.setStatus(retrievedItem.getStatus());
502         item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
503         item.setCreationTime(retrievedItem.getCreationTime());
504         item.setModificationTime(new Date());
505         item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
506         itemManager.update(item);
507     }
508
509     private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
510         VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
511         if (vspDetails.getVlmVersion() != null) {
512             vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
513         }
514         ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
515         Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
516         if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
517             activityLogManager
518                 .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
519             return Optional.of(validationResponse);
520         }
521         versioningManager.submit(vspId, version, message);
522         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
523         return Optional.empty();
524     }
525
526     private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
527         Map<String, Object> eventProperties = new HashMap<>();
528         eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
529         eventProperties.put(ITEM_ID, itemId);
530         if (version != null) {
531             eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
532             eventProperties.put(VERSION_ID, version.getId());
533         }
534         eventProperties.put(SUBMIT_DESCRIPTION, message);
535         eventProperties.put(PERMISSION_USER, userName);
536         Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
537         try {
538             notifier.notifySubscribers(syncEvent, userName);
539         } catch (Exception e) {
540             LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
541         }
542     }
543
544     private Response createPackage(String vspId, Version version) throws IOException {
545         Version retrievedVersion = versioningManager.get(vspId, version);
546         if (retrievedVersion.getStatus() != VersionStatus.Certified) {
547             throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
548         }
549         PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
550         return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
551     }
552
553     private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
554         Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
555             .getInfo(vspId, version);
556         if (candidateInfo.isPresent()) {
557             if (candidateInfo.get().getValidationDataStructure() != null) {
558                 vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
559             }
560             vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
561             vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
562         } else {
563             OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
564             if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
565                 if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
566                     vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
567                 }
568                 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
569                 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
570             }
571         }
572     }
573
574     private boolean userHasPermission(String itemId, String userId) {
575         return permissionsManager.getUserItemPermission(itemId, userId)
576             .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
577     }
578
579     private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
580         Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
581         if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
582             itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
583         } else {
584             itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
585             if (VersionStatus.Certified.name().equals(versionStatus)) {
586                 itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
587             } else if (VersionStatus.Draft.name().equals(versionStatus)) {
588                 itemPredicate = itemPredicate
589                     .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
590             }
591         }
592         return itemPredicate;
593     }
594
595     private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
596         Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
597         return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
598             .collect(Collectors.toList());
599     }
600
601     private class SyncEvent implements Event {
602
603         private final String eventType;
604         private final String originatorId;
605         private final Map<String, Object> attributes;
606         private final String entityId;
607
608         SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
609             this.eventType = eventType;
610             this.originatorId = originatorId;
611             this.attributes = attributes;
612             this.entityId = entityId;
613         }
614
615         @Override
616         public String getEventType() {
617             return eventType;
618         }
619
620         @Override
621         public String getOriginatorId() {
622             return originatorId;
623         }
624
625         @Override
626         public Map<String, Object> getAttributes() {
627             return attributes;
628         }
629
630         @Override
631         public String getEntityId() {
632             return entityId;
633         }
634     }
635 }