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