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