86e676020c396858551c0ed2323d10396b3f9ea2
[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.VendorSoftwareProducts;
102 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
103 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
104 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
105 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
106 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
107 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
108 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
109 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
110 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
111 import org.springframework.context.annotation.Scope;
112 import org.springframework.stereotype.Service;
113
114 @Named
115 @Service("vendorSoftwareProducts")
116 @Scope(value = "prototype")
117 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
118
119     private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
120     private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
121     private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
122     private static final String ATTACHMENT_FILENAME = "attachment; filename=";
123     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.";
124     private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
125     private static final Object VALIDATION_VSP_CACHE_LOCK = new Object();
126     private static ItemCreationDto cachedValidationVsp;
127     private final AsdcItemManager itemManager;
128     private final PermissionsManager permissionsManager;
129     private final VersioningManager versioningManager;
130     private final VendorSoftwareProductManager vendorSoftwareProductManager;
131     private final ActivityLogManager activityLogManager;
132     private final NotificationPropagationManager notifier;
133     private final UniqueValueUtil uniqueValueUtil;
134     private final ArtifactStorageManager artifactStorageManager;
135
136     public VendorSoftwareProductsImpl() {
137         this.itemManager = AsdcItemManagerFactory.getInstance().createInterface();
138         this.permissionsManager = PermissionsManagerFactory.getInstance().createInterface();
139         this.versioningManager = VersioningManagerFactory.getInstance().createInterface();
140         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
141         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
142         this.notifier = NotificationPropagationManagerFactory.getInstance().createInterface();
143         this.uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface());
144         this.artifactStorageManager = new StorageFactory().createArtifactStorageManager();
145     }
146
147     public VendorSoftwareProductsImpl(AsdcItemManager itemManager,
148                                       PermissionsManager permissionsManager,
149                                       VersioningManager versioningManager,
150                                       VendorSoftwareProductManager vendorSoftwareProductManager,
151                                       ActivityLogManager activityLogManager,
152                                       NotificationPropagationManager notifier,
153                                       UniqueValueUtil uniqueValueUtil,
154                                       ArtifactStorageManager artifactStorageManager) {
155         this.itemManager = itemManager;
156         this.permissionsManager = permissionsManager;
157         this.versioningManager = versioningManager;
158         this.vendorSoftwareProductManager = vendorSoftwareProductManager;
159         this.activityLogManager = activityLogManager;
160         this.notifier = notifier;
161         this.uniqueValueUtil = uniqueValueUtil;
162         this.artifactStorageManager = artifactStorageManager;
163     }
164
165     @Override
166     public Response createVsp(VspRequestDto vspRequestDto, String user) {
167         ItemCreationDto vspCreationDto = createVspItem(vspRequestDto, user);
168         return Response.ok(vspCreationDto).build();
169     }
170
171     private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) {
172         OnboardingMethod onboardingMethod = null;
173         try {
174             onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
175         } catch (IllegalArgumentException e) {
176             LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
177             throwUnknownOnboardingMethodException(e);
178         }
179         ItemCreationDto itemCreationDto = null;
180         if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) {
181             itemCreationDto = createItem(vspRequestDto, user, onboardingMethod);
182         } else {
183             throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
184         }
185         return itemCreationDto;
186     }
187
188     private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) {
189         Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
190         item.setType(ItemType.vsp.name());
191         item.setOwner(user);
192         item.setStatus(ItemStatus.ACTIVE);
193         item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
194         uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
195         item = itemManager.create(item);
196         uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
197         Version version = versioningManager.create(item.getId(), new Version(), null);
198         VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
199         vspDetails.setId(item.getId());
200         vspDetails.setVersion(version);
201         vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
202         vendorSoftwareProductManager.createVsp(vspDetails);
203         versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
204         ItemCreationDto itemCreationDto = new ItemCreationDto();
205         itemCreationDto.setItemId(item.getId());
206         itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
207         activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", ""));
208         return itemCreationDto;
209     }
210
211     private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
212         ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder();
213         throw new CoreException(onboardingMethodUpdateErrorCode, e);
214     }
215
216     @Override
217     public Response listVsps(String versionStatus, String itemStatus, String user) {
218         GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
219         MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
220         getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
221         return Response.ok(results).build();
222     }
223
224     @Override
225     public Response getVsp(String vspId, String versionId, String user) {
226         Version version = versioningManager.get(vspId, new Version(versionId));
227         VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
228         try {
229             HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> {
230                 vspDetails.setVersion(healedVersion);
231                 if (version.getStatus() == VersionStatus.Certified) {
232                     submitHealedVersion(vspDetails, versionId, user);
233                 }
234             });
235         } catch (Exception e) {
236             LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e);
237         }
238         VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
239         addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto);
240         return Response.ok(vspDetailsDto).build();
241     }
242
243     @Override
244     public Response getLatestVsp(final String vspId, final String user) {
245         final List<Version> versions = versioningManager.list(vspId);
246         final Version version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
247             .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
248             .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
249         return getVsp(vspId, version.getId(), user);
250     }
251
252     private void submitHealedVersion(VspDetails vspDetails, String baseVersionId, String user) {
253         try {
254             if (vspDetails.getVlmVersion() != null) {
255                 // sync vlm if not exists on user space
256                 versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
257             }
258             submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> {
259                 throw new IllegalStateException("Certified vsp after healing failed on validation");
260             });
261             vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
262         } catch (Exception ex) {
263             LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex);
264         }
265     }
266
267     @Override
268     public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) {
269         VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
270         vspDetails.setId(vspId);
271         vspDetails.setVersion(new Version(versionId));
272         vendorSoftwareProductManager.updateVsp(vspDetails);
273         updateVspItem(vspId, vspDescriptionDto);
274         return Response.ok().build();
275     }
276
277     @Override
278     public Response deleteVsp(String vspId, String user) {
279         Item vsp = itemManager.get(vspId);
280         if (!vsp.getType().equals(ItemType.vsp.name())) {
281             throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vsp with id %s does not exist.", vspId)).build()));
282         }
283         Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
284         if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
285             if (artifactStorageManager.isEnabled() && !deleteVspFromStorage(vspId)) {
286                 return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
287                     .entity(new Exception(Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId))).build();
288             }
289             return deleteVsp(vspId, user, vsp);
290         } else {
291             final var isVspArchived = getVspList(null, ItemStatus.ARCHIVED.name(), user).stream().anyMatch(item -> item.getId().equals(vspId));
292             if (isVspArchived) {
293                 if (artifactStorageManager.isEnabled() && !deleteVspFromStorage(vspId)) {
294                     return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
295                         .entity(new Exception(Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId))).build();
296                 }
297                 return deleteVsp(vspId, user, vsp);
298             }
299             return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
300         }
301     }
302
303     private boolean deleteVspFromStorage(final String vspId) {
304         try {
305             artifactStorageManager.delete(vspId);
306         } catch (final Exception e) {
307             LOGGER.error("Failed to delete VSP '{}'", vspId, e);
308             return false;
309         }
310         return true;
311     }
312
313     private Response deleteVsp(String vspId, String user, Item vsp) {
314         versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
315         itemManager.delete(vsp);
316         permissionsManager.deleteItemPermissions(vspId);
317         uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
318         notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
319         return Response.ok().build();
320     }
321
322     @Override
323     public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
324         throws IOException {
325         Version version = new Version(versionId);
326         if (request.getAction() == VendorSoftwareProductAction.Submit) {
327             if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
328                 return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
329             }
330             String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
331             Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
332             if (validationResponse.isPresent()) {
333                 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
334                     .applyMapping(validationResponse.get(), ValidationResponseDto.class);
335                 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
336             }
337             notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
338         } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
339             return createPackage(vspId, version);
340         }
341         return Response.ok().build();
342     }
343
344     @Override
345     public Response getValidationVsp(String user) {
346         ItemCreationDto validationVsp = retrieveValidationVsp();
347         return Response.ok(validationVsp).build();
348     }
349
350     private ItemCreationDto retrieveValidationVsp() {
351         synchronized (VALIDATION_VSP_CACHE_LOCK) {
352             if (cachedValidationVsp != null) {
353                 return cachedValidationVsp;
354             }
355             VspRequestDto validationVspRequest = new VspRequestDto();
356             validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
357             validationVspRequest.setName(VALIDATION_VSP_NAME);
358             try {
359                 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
360                 return cachedValidationVsp;
361             } catch (CoreException vspCreateException) {
362                 LOGGER.debug("Failed to create validation VSP", vspCreateException);
363                 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
364                     .equals(item.getName());
365                 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
366                         "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
367                     .getId();
368                 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
369                 cachedValidationVsp = new ItemCreationDto();
370                 cachedValidationVsp.setItemId(validationVspId);
371                 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
372                 return cachedValidationVsp;
373             }
374         }
375     }
376
377     @Override
378     public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
379         byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
380         if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
381             return Response.status(Response.Status.NOT_FOUND).build();
382         }
383         Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
384         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
385         return response.build();
386     }
387
388     @Override
389     public Response listPackages(String status, String category, String subCategory, String user) {
390         List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
391             .collect(Collectors.toList());
392         List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
393         packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
394         GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
395         MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
396         if (packageInfoList != null) {
397             for (PackageInfo packageInfo : packageInfoList) {
398                 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
399             }
400         }
401         return Response.ok(results).build();
402     }
403
404     @Override
405     public Response getTranslatedFile(String vspId, String versionId, String user) {
406         final List<Version> versions = versioningManager.list(vspId);
407         final Version version;
408         if (versionId == null) {
409             version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
410                 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
411                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
412         } else {
413             version = versions.stream()
414                 .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
415                 .findFirst()
416                 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
417             if (version.getStatus() != VersionStatus.Certified) {
418                 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
419             }
420         }
421         File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
422         Response.ResponseBuilder response = Response.ok(zipFile);
423         if (zipFile == null) {
424             return Response.status(Response.Status.NOT_FOUND).build();
425         }
426         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
427         return response.build();
428     }
429
430     @Override
431     public Response getQuestionnaire(String vspId, String versionId, String user) {
432         QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
433         if (questionnaireResponse.getErrorMessage() != null) {
434             return Response.status(Response.Status.EXPECTATION_FAILED)
435                 .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
436                 .build();
437         }
438         QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
439             .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
440         return Response.ok(result).build();
441     }
442
443     @Override
444     public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
445         vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
446         return Response.ok().build();
447     }
448
449     @Override
450     public Response heal(String vspId, String versionId, String user) {
451         HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
452         return Response.ok().build();
453     }
454
455     @Override
456     public Response getVspInformationArtifact(String vspId, String versionId, String user) {
457         File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
458         Response.ResponseBuilder response = Response.ok(textInformationArtifact);
459         if (textInformationArtifact == null) {
460             return Response.status(Response.Status.NOT_FOUND).build();
461         }
462         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
463         return response.build();
464     }
465
466     @Override
467     public Response listComputes(String vspId, String version, String user) {
468         Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
469         MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
470         GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
471         for (ComputeEntity compute : computes) {
472             results.add(mapper.applyMapping(compute, VspComputeDto.class));
473         }
474         return Response.ok(results).build();
475     }
476
477     private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
478         Item retrievedItem = itemManager.get(vspId);
479         Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
480         item.setId(vspId);
481         item.setType(retrievedItem.getType());
482         item.setOwner(retrievedItem.getOwner());
483         item.setStatus(retrievedItem.getStatus());
484         item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
485         item.setCreationTime(retrievedItem.getCreationTime());
486         item.setModificationTime(new Date());
487         item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
488         itemManager.update(item);
489     }
490
491     private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
492         VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
493         if (vspDetails.getVlmVersion() != null) {
494             vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
495         }
496         ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
497         Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
498         if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
499             activityLogManager
500                 .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
501             return Optional.of(validationResponse);
502         }
503         versioningManager.submit(vspId, version, message);
504         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
505         return Optional.empty();
506     }
507
508     private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
509         Map<String, Object> eventProperties = new HashMap<>();
510         eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
511         eventProperties.put(ITEM_ID, itemId);
512         if (version != null) {
513             eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
514             eventProperties.put(VERSION_ID, version.getId());
515         }
516         eventProperties.put(SUBMIT_DESCRIPTION, message);
517         eventProperties.put(PERMISSION_USER, userName);
518         Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
519         try {
520             notifier.notifySubscribers(syncEvent, userName);
521         } catch (Exception e) {
522             LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
523         }
524     }
525
526     private Response createPackage(String vspId, Version version) throws IOException {
527         Version retrievedVersion = versioningManager.get(vspId, version);
528         if (retrievedVersion.getStatus() != VersionStatus.Certified) {
529             throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
530         }
531         PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
532         return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
533     }
534
535     private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
536         Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
537             .getInfo(vspId, version);
538         if (candidateInfo.isPresent()) {
539             if (candidateInfo.get().getValidationDataStructure() != null) {
540                 vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
541             }
542             vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
543             vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
544         } else {
545             OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
546             if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
547                 if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
548                     vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
549                 }
550                 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
551                 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
552             }
553         }
554     }
555
556     private boolean userHasPermission(String itemId, String userId) {
557         return permissionsManager.getUserItemPermission(itemId, userId)
558             .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
559     }
560
561     private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
562         Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
563         if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
564             itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
565         } else {
566             itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
567             if (VersionStatus.Certified.name().equals(versionStatus)) {
568                 itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
569             } else if (VersionStatus.Draft.name().equals(versionStatus)) {
570                 itemPredicate = itemPredicate
571                     .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
572             }
573         }
574         return itemPredicate;
575     }
576
577     private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
578         Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
579         return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
580             .collect(Collectors.toList());
581     }
582
583     private class SyncEvent implements Event {
584
585         private final String eventType;
586         private final String originatorId;
587         private final Map<String, Object> attributes;
588         private final String entityId;
589
590         SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
591             this.eventType = eventType;
592             this.originatorId = originatorId;
593             this.attributes = attributes;
594             this.entityId = entityId;
595         }
596
597         @Override
598         public String getEventType() {
599             return eventType;
600         }
601
602         @Override
603         public String getOriginatorId() {
604             return originatorId;
605         }
606
607         @Override
608         public Map<String, Object> getAttributes() {
609             return attributes;
610         }
611
612         @Override
613         public String getEntityId() {
614             return entityId;
615         }
616     }
617 }