480b83bf8fc1472cc8c87043de243c995718640d
[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
17
18 package org.openecomp.sdcrests.vsp.rest.services;
19
20 import org.apache.commons.collections4.MapUtils;
21 import org.openecomp.core.dao.UniqueValueDaoFactory;
22 import org.openecomp.core.util.UniqueValueUtil;
23 import org.openecomp.sdc.activitylog.ActivityLogManager;
24 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
25 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
26 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
27 import org.openecomp.sdc.common.errors.CoreException;
28 import org.openecomp.sdc.common.errors.ErrorCode;
29 import org.openecomp.sdc.common.errors.Messages;
30 import org.openecomp.sdc.datatypes.error.ErrorLevel;
31 import org.openecomp.sdc.datatypes.error.ErrorMessage;
32 import org.openecomp.sdc.datatypes.model.ItemType;
33 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
34 import org.openecomp.sdc.itempermissions.ItemPermissionsManager;
35 import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory;
36 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
37 import org.openecomp.sdc.logging.api.Logger;
38 import org.openecomp.sdc.logging.api.LoggerFactory;
39 import org.openecomp.sdc.logging.messages.AuditMessages;
40 import org.openecomp.sdc.notification.dtos.Event;
41 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
42 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
43 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
44 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
45 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
46 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
49 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
50 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
51 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
52 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
53 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
54 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
55 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
57 import org.openecomp.sdc.versioning.AsdcItemManager;
58 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
59 import org.openecomp.sdc.versioning.VersioningManager;
60 import org.openecomp.sdc.versioning.VersioningManagerFactory;
61 import org.openecomp.sdc.versioning.dao.types.Version;
62 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
63 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
64 import org.openecomp.sdc.versioning.types.Item;
65 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
66 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
67 import org.openecomp.sdcrests.item.types.ItemCreationDto;
68 import org.openecomp.sdcrests.item.types.VersionDto;
69 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
70 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
71 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
72 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
73 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
74 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
75 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
76 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
77 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
78 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
79 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
80 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
81 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
82 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
83 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
84 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
85 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
86 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
87 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
88 import org.springframework.context.annotation.Scope;
89 import org.springframework.stereotype.Service;
90
91 import java.io.File;
92 import java.io.IOException;
93 import java.util.Collection;
94 import java.util.Comparator;
95 import java.util.HashMap;
96 import java.util.List;
97 import java.util.Map;
98 import java.util.Objects;
99 import java.util.Optional;
100 import java.util.function.Predicate;
101 import javax.inject.Named;
102 import javax.ws.rs.core.Response;
103
104 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
105 import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
106 import static org.openecomp.sdc.logging.messages.AuditMessages.SUBMIT_VSP_ERROR;
107 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
108 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.VALIDATION_VSP_NAME;
109 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
110 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
111 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
112 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
113 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
114
115 @Named
116 @Service("vendorSoftwareProducts")
117 @Scope(value = "prototype")
118 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
119
120   private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
121   private static final String ATTACHMENT_FILENAME = "attachment; filename=";
122   private static final String SUBMIT_HEALED_VERSION_ERROR =
123       "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
126   private static ItemCreationDto validationVsp;
127
128   private final AsdcItemManager asdcItemManager = AsdcItemManagerFactory.getInstance()
129       .createInterface();
130   private final ItemPermissionsManager permissionsManager =
131       ItemPermissionsManagerFactory.getInstance().createInterface();
132   private final VersioningManager versioningManager =
133       VersioningManagerFactory.getInstance().createInterface();
134   private final VendorSoftwareProductManager vendorSoftwareProductManager =
135       VspManagerFactory.getInstance().createInterface();
136   private final ActivityLogManager activityLogManager =
137       ActivityLogManagerFactory.getInstance().createInterface();
138   private final NotificationPropagationManager notifier =
139       NotificationPropagationManagerFactory.getInstance().createInterface();
140   private final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory
141       .getInstance().createInterface());
142
143   @Override
144   public Response createVsp(VspRequestDto vspRequestDto, String user) {
145
146     OnboardingMethod onboardingMethod = null;
147     try {
148       onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
149     } catch (IllegalArgumentException e) {
150       LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
151       throwUnknownOnboardingMethodException(e);
152     }
153     ItemCreationDto itemCreationDto = null;
154     if (onboardingMethod == OnboardingMethod.NetworkPackage
155         || onboardingMethod == OnboardingMethod.Manual) {
156       itemCreationDto = getItemCreationDto(vspRequestDto, user, onboardingMethod);
157
158     } else {
159       throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
160     }
161
162     return Response.ok(itemCreationDto).build();
163   }
164
165   private ItemCreationDto getItemCreationDto(VspRequestDto vspRequestDto,
166                                              String user,
167                                              OnboardingMethod onboardingMethod) {
168
169     Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
170     item.setType(ItemType.vsp.name());
171     item.setOwner(user);
172     item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
173
174     uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
175     item = asdcItemManager.create(item);
176     uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
177
178     Version version = versioningManager.create(item.getId(), new Version(), null);
179
180     VspDetails vspDetails =
181         new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
182     vspDetails.setId(item.getId());
183     vspDetails.setVersion(version);
184     vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
185
186     vendorSoftwareProductManager.createVsp(vspDetails);
187     versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
188     ItemCreationDto itemCreationDto = new ItemCreationDto();
189     itemCreationDto.setItemId(item.getId());
190     itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
191
192     activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version,
193         ActivityType.Create, user, true, "", ""));
194     return itemCreationDto;
195   }
196
197   private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
198     ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder
199         .getInvalidOnboardingMethodErrorBuilder();
200     throw new CoreException(onboardingMethodUpdateErrorCode,e);
201   }
202
203   @Override
204   public Response listVsps(String versionStatus, String user) {
205     Predicate<Item> itemPredicate;
206     if (VersionStatus.Certified.name().equals(versionStatus)) {
207       itemPredicate = item -> ItemType.vsp.name().equals(item.getType())
208           && item.getVersionStatusCounters().containsKey(VersionStatus.Certified);
209
210     } else if (VersionStatus.Draft.name().equals(versionStatus)) {
211       itemPredicate = item -> ItemType.vsp.name().equals(item.getType())
212           && item.getVersionStatusCounters().containsKey(VersionStatus.Draft)
213           && userHasPermission(item.getId(), user);
214
215     } else {
216       itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
217     }
218
219     GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
220     MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
221     asdcItemManager.list(itemPredicate).stream()
222         .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
223         .forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
224
225     return Response.ok(results).build();
226   }
227
228   @Override
229   public Response getVsp(String vspId, String versionId, String user) {
230     Version version = versioningManager.get(vspId, new Version(versionId));
231     VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
232     vspDetails.setWritetimeMicroSeconds(version.getModificationTime().getTime());
233
234     try {
235       Optional<Version> healedVersion = HealingManagerFactory.getInstance().createInterface()
236           .healItemVersion(vspId, version, ItemType.vsp, false);
237
238       healedVersion.ifPresent(version1 -> {
239         vspDetails.setVersion(version1);
240         if (version.getStatus() == VersionStatus.Certified) {
241           submitHealedVersion(vspId, version1, versionId, user);
242         }
243       });
244     } catch (Exception e) {
245       LOGGER.error(
246           String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId),
247           e);
248     }
249
250     VspDetailsDto vspDetailsDto =
251         new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
252     addNetworkPackageInfo(vspId, version, vspDetailsDto);
253
254     return Response.ok(vspDetailsDto).build();
255   }
256
257   private void submitHealedVersion(String vspId, Version healedVersion, String baseVersionId,
258                                    String user) {
259     try {
260       Optional<ValidationResponse>
261           validationResponse = submit(vspId, healedVersion, "Submit healed Vsp", user);
262       // TODO: 8/9/2017 before collaboration checkout was done at this scenario (equivalent
263       // to new version in collaboration). need to decide what should be done now.
264       validationResponse.ifPresent(validationResponse1 -> {
265         throw new IllegalStateException("Certified vsp after healing failed on validation");
266       });
267       vendorSoftwareProductManager.createPackage(vspId, healedVersion);
268     } catch (Exception ex) {
269       LOGGER.error(
270           String.format(SUBMIT_HEALED_VERSION_ERROR, vspId, healedVersion.getId(), baseVersionId),
271           ex);
272     }
273   }
274
275   @Override
276   public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto,
277                             String user) {
278     VspDetails vspDetails =
279         new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
280     vspDetails.setId(vspId);
281     vspDetails.setVersion(new Version(versionId));
282
283     vendorSoftwareProductManager.updateVsp(vspDetails);
284
285     return Response.ok().build();
286   }
287
288   @Override
289   public Response deleteVsp(String vspId, String user) {
290     Item vsp = asdcItemManager.get(vspId);
291
292     if(!vsp.getType().equals(ItemType.vsp.name())){
293       throw new CoreException((new ErrorCode.ErrorCodeBuilder()
294               .withMessage(String.format("Vsp with id %s does not exist.",
295                       vspId)).build()));
296     }
297
298     Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
299     if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
300       asdcItemManager.delete(vsp);
301       permissionsManager.deleteItemPermissions(vspId);
302       uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
303       notifyUsers(vspId, vsp.getName(), null, "VSP was deleted", user,
304           NotificationEventTypes.DELETE);
305
306       return Response.ok().build();
307     } else {
308       return Response.status(Response.Status.FORBIDDEN)
309           .entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
310     }
311   }
312
313   @Override
314   public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request,
315                                              String vspId, String versionId,
316                                              String user) throws IOException {
317     Version version = new Version(versionId);
318
319     if (request.getAction() == VendorSoftwareProductAction.Submit) {
320       if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
321         return Response.status(Response.Status.FORBIDDEN)
322             .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
323       }
324       String message = request.getSubmitRequest() == null ? "Submit"
325           : request.getSubmitRequest().getMessage();
326       Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
327
328       if (validationResponse.isPresent()) {
329         ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
330             .applyMapping(validationResponse.get(), ValidationResponseDto.class);
331         return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto)
332             .build();
333       }
334
335       notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
336
337     } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
338       return createPackage(vspId, version);
339     }
340
341     return Response.ok().build();
342   }
343
344   @Override
345   public Response getValidationVsp(String user) throws Exception {
346     if (validationVsp != null) {
347       return Response.ok(validationVsp).build();
348     }
349
350     VspRequestDto validationVspRequest = new VspRequestDto();
351     validationVspRequest.setOnboardingMethod("HEAT");
352     validationVspRequest.setName(VALIDATION_VSP_NAME);
353
354     try {
355       validationVsp = (ItemCreationDto) createVsp(validationVspRequest, user).getEntity();
356       return Response.ok(validationVsp).build();
357
358     } catch (CoreException validationVspAlreadyExistException) {
359       // find validationVsp
360       String validationVspId = asdcItemManager.list(item ->
361           ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME.equals(item.getName()))
362           .stream().findFirst().orElseThrow(() -> new IllegalStateException("Vsp with name %s "
363               + "does not exist even though the name exists according to unique value util"))
364           .getId();
365       Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
366
367       validationVsp = new ItemCreationDto();
368       validationVsp.setItemId(validationVspId);
369       validationVsp
370           .setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
371
372       return Response.ok(validationVsp).build();
373     }
374   }
375
376   @Override
377   public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
378     byte[] orchestrationTemplateFile =
379         vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
380
381     if (orchestrationTemplateFile == null) {
382       return Response.status(Response.Status.NOT_FOUND).build();
383     }
384     Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
385     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
386     return response.build();
387   }
388
389   @Override
390   public Response listPackages(String category, String subCategory, String user) {
391     List<PackageInfo> packageInfoList =
392         vendorSoftwareProductManager.listPackages(category, subCategory);
393
394     GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
395     MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
396
397     if (packageInfoList != null) {
398       for (PackageInfo packageInfo : packageInfoList) {
399         results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
400       }
401     }
402     return Response.ok(results).build();
403   }
404
405   @Override
406   public Response getTranslatedFile(String vspId, String versionName, String user) {
407     List<Version> versions = versioningManager.list(vspId);
408     Version version;
409     if (versionName == null) {
410       version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
411           .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
412           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
413     } else {
414       version = versions.stream().filter(ver -> versionName.equals(ver.getName()))
415           .findFirst()
416           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
417
418       if (version.getStatus() != VersionStatus.Certified) {
419         throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
420       }
421     }
422
423     File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
424
425     Response.ResponseBuilder response = Response.ok(zipFile);
426     if (zipFile == null) {
427       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId);
428       return Response.status(Response.Status.NOT_FOUND).build();
429     }
430     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
431
432     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId);
433     return response.build();
434   }
435
436   @Override
437   public Response getQuestionnaire(String vspId, String versionId, String user) {
438     QuestionnaireResponse questionnaireResponse =
439         vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
440
441     if (questionnaireResponse.getErrorMessage() != null) {
442       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
443           new MapQuestionnaireResponseToQuestionnaireResponseDto()
444               .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build();
445     }
446
447     QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
448         .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
449     return Response.ok(result).build();
450   }
451
452   @Override
453   public Response updateQuestionnaire(String questionnaireData, String vspId, String
454       versionId, String user) {
455     vendorSoftwareProductManager
456         .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
457     return Response.ok().build();
458   }
459
460   @Override
461   public Response heal(String vspId, String versionId, String user) {
462     HealingManagerFactory.getInstance().createInterface()
463         .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
464     return Response.ok().build();
465   }
466
467   @Override
468   public Response getVspInformationArtifact(String vspId, String versionId, String user) {
469     File textInformationArtifact =
470         vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
471
472     Response.ResponseBuilder response = Response.ok(textInformationArtifact);
473     if (textInformationArtifact == null) {
474       return Response.status(Response.Status.NOT_FOUND).build();
475     }
476     response
477         .header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
478     return response.build();
479   }
480
481   @Override
482   public Response listComputes(String vspId, String version, String user) {
483
484     Collection<ComputeEntity> computes =
485         vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
486
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
493     return Response.ok(results).build();
494   }
495
496   private Optional<ValidationResponse> submit(String vspId, Version version, String message,
497                                               String user) throws IOException {
498
499     ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspId, version);
500     Map<String, List<ErrorMessage>> compilationErrors =
501         vendorSoftwareProductManager.compile(vspId, version);
502     if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
503       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP_FAIL + vspId);
504       if (validationResponse.getVspErrors() != null) {
505         validationResponse.getVspErrors().forEach(errorCode -> LOGGER.audit(AuditMessages
506             .AUDIT_MSG + String.format(SUBMIT_VSP_ERROR, errorCode.message(), vspId)));
507       }
508       if (validationResponse.getUploadDataErrors() != null) {
509         validationResponse.getUploadDataErrors().values().forEach(errorMessages
510             -> printAuditForErrors(errorMessages, vspId, SUBMIT_VSP_ERROR));
511       }
512       activityLogManager.logActivity(
513           new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false,
514               "Failed on validation before submit", ""));
515       return Optional.of(validationResponse);
516     }
517
518     versioningManager.submit(vspId, version, message);
519
520     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId);
521     activityLogManager.logActivity(
522         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,
527                            String userName, NotificationEventTypes eventType) {
528     Map<String, Object> eventProperties = new HashMap<>();
529     eventProperties.put(ITEM_NAME, itemName == null ? asdcItemManager.get(itemId).getName() : itemName);
530     eventProperties.put(ITEM_ID, itemId);
531
532     if (version != null) {
533       eventProperties.put(VERSION_NAME, version.getName() == null
534           ? versioningManager.get(itemId, version).getName()
535           : version.getName());
536       eventProperties.put(VERSION_ID, version.getId());
537     }
538
539     eventProperties.put(SUBMIT_DESCRIPTION, message);
540     eventProperties.put(PERMISSION_USER, userName);
541
542     Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
543     try {
544       notifier.notifySubscribers(syncEvent, userName);
545     } catch (Exception e) {
546       LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId);
547     }
548   }
549
550   private class SyncEvent implements Event {
551
552     private final String eventType;
553     private final String originatorId;
554     private final Map<String, Object> attributes;
555     private final String entityId;
556
557     SyncEvent(String eventType, String originatorId,
558               Map<String, Object> attributes, String entityId) {
559       this.eventType = eventType;
560       this.originatorId = originatorId;
561       this.attributes = attributes;
562       this.entityId = entityId;
563     }
564
565     @Override
566     public String getEventType() {
567       return eventType;
568     }
569
570     @Override
571     public String getOriginatorId() {
572       return originatorId;
573     }
574
575     @Override
576     public Map<String, Object> getAttributes() {
577       return attributes;
578     }
579
580     @Override
581     public String getEntityId() {
582       return entityId;
583     }
584   }
585
586   private Response createPackage(String vspId, Version version) throws IOException {
587     Version retrievedVersion = versioningManager.get(vspId, version);
588     if (retrievedVersion.getStatus() != VersionStatus.Certified) {
589       throw new CoreException(
590           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
591               .build());
592     }
593     PackageInfo packageInfo =
594         vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
595     return Response.ok(packageInfo == null
596         ? null
597         : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class))
598         .build();
599   }
600
601   private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
602     OrchestrationTemplateCandidateData candidateInfo =
603         OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
604             .getInfo(vspId, version);
605     if (Objects.nonNull(candidateInfo) && Objects.nonNull(candidateInfo.getFileSuffix())) {
606       vspDetailsDto.setValidationData(candidateInfo.getValidationDataStructure());
607       vspDetailsDto.setNetworkPackageName(candidateInfo.getFileName());
608       vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.getFileSuffix());
609     } else {
610       OrchestrationTemplateEntity orchestrationTemplateInfo =
611           vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
612       if (Objects.nonNull(orchestrationTemplateInfo)) {
613         vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
614         vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
615         vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
616       }
617     }
618   }
619
620   private boolean userHasPermission(String itemId, String userId) {
621     String permission = permissionsManager.getUserItemPermiission(itemId, userId);
622     return permission != null && permission
623         .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name());
624   }
625
626   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
627     errorList.forEach(errorMessage -> {
628       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
629         LOGGER.audit(
630             AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId));
631       }
632     });
633   }
634 }