09cb0945b17a57ef8e4ac436ddc68ca7624c0314
[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     Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
289     if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
290       itemManager.delete(vsp);
291       permissionsManager.deleteItemPermissions(vspId);
292       UniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
293       notifyUsers(vspId, vsp.getName(), null, "VSP was deleted", user,
294           NotificationEventTypes.DELETE);
295
296       return Response.ok().build();
297     } else {
298       return Response.status(Response.Status.PRECONDITION_FAILED)
299           .entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
300     }
301   }
302
303   @Override
304   public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request,
305                                              String vspId, String versionId,
306                                              String user) throws IOException {
307     Version version = new Version(versionId);
308
309     if (request.getAction() == VendorSoftwareProductAction.Submit) {
310       if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
311         return Response.status(Response.Status.FORBIDDEN)
312             .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
313       }
314       String message = request.getSubmitRequest() == null ? "Submit"
315           : request.getSubmitRequest().getMessage();
316       Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
317
318       if (validationResponse.isPresent()) {
319         ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
320             .applyMapping(validationResponse.get(), ValidationResponseDto.class);
321         return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto)
322             .build();
323       }
324
325       notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
326
327     } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
328       return createPackage(vspId, version);
329     }
330
331     return Response.ok().build();
332   }
333
334   @Override
335   public Response getValidationVsp(String user) throws Exception {
336     if (validationVsp != null) {
337       return Response.ok(validationVsp).build();
338     }
339
340     VspRequestDto validationVspRequest = new VspRequestDto();
341     validationVspRequest.setOnboardingMethod("HEAT");
342     validationVspRequest.setName(VALIDATION_VSP_NAME);
343
344     try {
345       validationVsp = (ItemCreationDto) createVsp(validationVspRequest, user).getEntity();
346       return Response.ok(validationVsp).build();
347
348     } catch (CoreException validationVspAlreadyExistException) {
349       // find validationVsp
350       String validationVspId = itemManager.list(item ->
351           ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME.equals(item.getName()))
352           .stream().findFirst().orElseThrow(() -> new IllegalStateException("Vsp with name %s "
353               + "does not exist even though the name exists according to unique value util"))
354           .getId();
355       Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
356
357       validationVsp = new ItemCreationDto();
358       validationVsp.setItemId(validationVspId);
359       validationVsp
360           .setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
361
362       return Response.ok(validationVsp).build();
363     }
364   }
365
366   @Override
367   public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
368     byte[] orchestrationTemplateFile =
369         vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
370
371     if (orchestrationTemplateFile == null) {
372       return Response.status(Response.Status.NOT_FOUND).build();
373     }
374     Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
375     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
376     return response.build();
377   }
378
379   @Override
380   public Response listPackages(String category, String subCategory, String user) {
381     List<PackageInfo> packageInfoList =
382         vendorSoftwareProductManager.listPackages(category, subCategory);
383
384     GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
385     MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
386
387     if (packageInfoList != null) {
388       for (PackageInfo packageInfo : packageInfoList) {
389         results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
390       }
391     }
392     return Response.ok(results).build();
393   }
394
395   @Override
396   public Response getTranslatedFile(String vspId, String versionName, String user) {
397     List<Version> versions = versioningManager.list(vspId);
398     Version version;
399     if (versionName == null) {
400       version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
401           .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
402           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
403     } else {
404       version = versions.stream().filter(ver -> versionName.equals(ver.getName()))
405           .findFirst()
406           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
407
408       if (version.getStatus() != VersionStatus.Certified) {
409         throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
410       }
411     }
412
413     File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
414
415     Response.ResponseBuilder response = Response.ok(zipFile);
416     if (zipFile == null) {
417       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId);
418       return Response.status(Response.Status.NOT_FOUND).build();
419     }
420     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
421
422     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId);
423     return response.build();
424   }
425
426   @Override
427   public Response getQuestionnaire(String vspId, String versionId, String user) {
428     QuestionnaireResponse questionnaireResponse =
429         vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
430
431     if (questionnaireResponse.getErrorMessage() != null) {
432       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
433           new MapQuestionnaireResponseToQuestionnaireResponseDto()
434               .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build();
435     }
436
437     QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
438         .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
439     return Response.ok(result).build();
440   }
441
442   @Override
443   public Response updateQuestionnaire(String questionnaireData, String vspId, String
444       versionId, String user) {
445     vendorSoftwareProductManager
446         .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
447     return Response.ok().build();
448   }
449
450   @Override
451   public Response heal(String vspId, String versionId, String user) {
452     HealingManagerFactory.getInstance().createInterface()
453         .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
454     return Response.ok().build();
455   }
456
457   @Override
458   public Response getVspInformationArtifact(String vspId, String versionId, String user) {
459     File textInformationArtifact =
460         vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
461
462     Response.ResponseBuilder response = Response.ok(textInformationArtifact);
463     if (textInformationArtifact == null) {
464       return Response.status(Response.Status.NOT_FOUND).build();
465     }
466     response
467         .header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
468     return response.build();
469   }
470
471   @Override
472   public Response listComputes(String vspId, String version, String user) {
473
474     Collection<ComputeEntity> computes =
475         vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
476
477     MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
478     GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
479     for (ComputeEntity compute : computes) {
480       results.add(mapper.applyMapping(compute, VspComputeDto.class));
481     }
482
483     return Response.ok(results).build();
484   }
485
486   private Optional<ValidationResponse> submit(String vspId, Version version, String message,
487                                               String user) throws IOException {
488
489     ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspId, version);
490     Map<String, List<ErrorMessage>> compilationErrors =
491         vendorSoftwareProductManager.compile(vspId, version);
492     if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
493       LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP_FAIL + vspId);
494       if (validationResponse.getVspErrors() != null) {
495         validationResponse.getVspErrors().forEach(errorCode -> LOGGER.audit(AuditMessages
496             .AUDIT_MSG + String.format(SUBMIT_VSP_ERROR, errorCode.message(), vspId)));
497       }
498       if (validationResponse.getUploadDataErrors() != null) {
499         validationResponse.getUploadDataErrors().values().forEach(errorMessages
500             -> printAuditForErrors(errorMessages, vspId, SUBMIT_VSP_ERROR));
501       }
502       activityLogManager.logActivity(
503           new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false,
504               "Failed on validation before submit", ""));
505       return Optional.of(validationResponse);
506     }
507
508     versioningManager.submit(vspId, version, message);
509
510     LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId);
511     activityLogManager.logActivity(
512         new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
513     return Optional.empty();
514   }
515
516   private void notifyUsers(String itemId, String itemName, Version version, String message,
517                            String userName, NotificationEventTypes eventType) {
518     Map<String, Object> eventProperties = new HashMap<>();
519     eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
520     eventProperties.put(ITEM_ID, itemId);
521
522     if (version != null) {
523       eventProperties.put(VERSION_NAME, version.getName() == null
524           ? versioningManager.get(itemId, version).getName()
525           : version.getName());
526       eventProperties.put(VERSION_ID, version.getId());
527     }
528
529     eventProperties.put(SUBMIT_DESCRIPTION, message);
530     eventProperties.put(PERMISSION_USER, userName);
531
532     Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
533     try {
534       notifier.notifySubscribers(syncEvent, userName);
535     } catch (Exception e) {
536       LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId);
537     }
538   }
539
540   private class SyncEvent implements Event {
541
542     private final String eventType;
543     private final String originatorId;
544     private final Map<String, Object> attributes;
545     private final String entityId;
546
547     SyncEvent(String eventType, String originatorId,
548               Map<String, Object> attributes, String entityId) {
549       this.eventType = eventType;
550       this.originatorId = originatorId;
551       this.attributes = attributes;
552       this.entityId = entityId;
553     }
554
555     @Override
556     public String getEventType() {
557       return eventType;
558     }
559
560     @Override
561     public String getOriginatorId() {
562       return originatorId;
563     }
564
565     @Override
566     public Map<String, Object> getAttributes() {
567       return attributes;
568     }
569
570     @Override
571     public String getEntityId() {
572       return entityId;
573     }
574   }
575
576   private Response createPackage(String vspId, Version version) throws IOException {
577     Version retrievedVersion = versioningManager.get(vspId, version);
578     if (retrievedVersion.getStatus() != VersionStatus.Certified) {
579       throw new CoreException(
580           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
581               .build());
582     }
583     PackageInfo packageInfo =
584         vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
585     return Response.ok(packageInfo == null
586         ? null
587         : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class))
588         .build();
589   }
590
591   private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
592     OrchestrationTemplateCandidateData candidateInfo =
593         OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
594             .getInfo(vspId, version);
595     if (Objects.nonNull(candidateInfo) && Objects.nonNull(candidateInfo.getFileSuffix())) {
596       vspDetailsDto.setValidationData(candidateInfo.getValidationDataStructure());
597       vspDetailsDto.setNetworkPackageName(candidateInfo.getFileName());
598       vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.getFileSuffix());
599     } else {
600       OrchestrationTemplateEntity orchestrationTemplateInfo =
601           vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
602       if (Objects.nonNull(orchestrationTemplateInfo)) {
603         vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
604         vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
605         vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
606       }
607     }
608   }
609
610   private boolean userHasPermission(String itemId, String userId) {
611     String permission = permissionsManager.getUserItemPermiission(itemId, userId);
612     return permission != null && permission
613         .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name());
614   }
615
616   private void printAuditForErrors(List<ErrorMessage> errorList, String vspId, String auditType) {
617     errorList.forEach(errorMessage -> {
618       if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) {
619         LOGGER.audit(
620             AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId));
621       }
622     });
623   }
624 }