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