be196bf326ebdbfa70d03bf34531db8019f55712
[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 package org.openecomp.sdcrests.vsp.rest.services;
18
19 import org.apache.commons.collections4.MapUtils;
20 import org.openecomp.core.dao.UniqueValueDaoFactory;
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.ErrorMessage;
30 import org.openecomp.sdc.datatypes.model.ItemType;
31 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
32 import org.openecomp.sdc.itempermissions.ItemPermissionsManager;
33 import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory;
34 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37 import org.openecomp.sdc.notification.dtos.Event;
38 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
39 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
40 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
41 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
42 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
43 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
44 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
45 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
46 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
49 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
50 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
51 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
52 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
53 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
54 import org.openecomp.sdc.versioning.AsdcItemManager;
55 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
56 import org.openecomp.sdc.versioning.VersioningManager;
57 import org.openecomp.sdc.versioning.VersioningManagerFactory;
58 import org.openecomp.sdc.versioning.dao.types.Version;
59 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
60 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
61 import org.openecomp.sdc.versioning.types.Item;
62 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
63 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
64 import org.openecomp.sdcrests.item.types.ItemCreationDto;
65 import org.openecomp.sdcrests.item.types.VersionDto;
66 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
67 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
68 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
69 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
70 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
71 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
72 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
73 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
74 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
75 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
76 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
77 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
78 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
79 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
80 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
81 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
82 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
83 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
84 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
85 import org.springframework.context.annotation.Scope;
86 import org.springframework.stereotype.Service;
87
88 import javax.inject.Named;
89 import javax.ws.rs.core.Response;
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
101 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
102 import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
103 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
104 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.VALIDATION_VSP_NAME;
105 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
106 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
107 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
108 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
109 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
110
111 @Named
112 @Service("vendorSoftwareProducts")
113 @Scope(value = "prototype")
114 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
115
116   private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
117   private static final String ATTACHMENT_FILENAME = "attachment; filename=";
118   private static final String SUBMIT_HEALED_VERSION_ERROR =
119       "VSP Id %s: Error while submitting version %s created based on Certified version %s for healing purpose.";
120   private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
121
122   private static ItemCreationDto validationVsp;
123
124   private final AsdcItemManager itemManager = AsdcItemManagerFactory.getInstance()
125       .createInterface();
126   private final ItemPermissionsManager permissionsManager =
127       ItemPermissionsManagerFactory.getInstance().createInterface();
128   private final VersioningManager versioningManager =
129       VersioningManagerFactory.getInstance().createInterface();
130   private final VendorSoftwareProductManager vendorSoftwareProductManager =
131       VspManagerFactory.getInstance().createInterface();
132   private final ActivityLogManager activityLogManager =
133       ActivityLogManagerFactory.getInstance().createInterface();
134   private final NotificationPropagationManager notifier =
135       NotificationPropagationManagerFactory.getInstance().createInterface();
136   private final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory
137       .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(
156           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 = itemManager.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     itemManager.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 = itemManager.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       versioningManager.list(vspId)
298           .forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
299       itemManager.delete(vsp);
300       permissionsManager.deleteItemPermissions(vspId);
301       uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
302       notifyUsers(vspId, vsp.getName(), null, "VSP was deleted", user,
303           NotificationEventTypes.DELETE);
304
305       return Response.ok().build();
306     } else {
307       return Response.status(Response.Status.FORBIDDEN)
308           .entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
309     }
310   }
311
312   @Override
313   public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request,
314                                              String vspId, String versionId,
315                                              String user) throws IOException {
316     Version version = new Version(versionId);
317
318     if (request.getAction() == VendorSoftwareProductAction.Submit) {
319       if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
320         return Response.status(Response.Status.FORBIDDEN)
321             .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
322       }
323       String message = request.getSubmitRequest() == null ? "Submit"
324           : request.getSubmitRequest().getMessage();
325       Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
326
327       if (validationResponse.isPresent()) {
328         ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
329             .applyMapping(validationResponse.get(), ValidationResponseDto.class);
330         return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto)
331             .build();
332       }
333
334       notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
335
336     } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
337       return createPackage(vspId, version);
338     }
339
340     return Response.ok().build();
341   }
342
343   @Override
344   public Response getValidationVsp(String user) {
345     if (validationVsp != null) {
346       return Response.ok(validationVsp).build();
347     }
348
349     VspRequestDto validationVspRequest = new VspRequestDto();
350     validationVspRequest.setOnboardingMethod("HEAT");
351     validationVspRequest.setName(VALIDATION_VSP_NAME);
352
353     try {
354       validationVsp = (ItemCreationDto) createVsp(validationVspRequest, user).getEntity();
355       return Response.ok(validationVsp).build();
356
357     } catch (CoreException validationVspAlreadyExistException) {
358       // find validationVsp
359       String validationVspId = itemManager.list(item ->
360           ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME.equals(item.getName()))
361           .stream().findFirst().orElseThrow(() -> new IllegalStateException("Vsp with name %s "
362               + "does not exist even though the name exists according to unique value util"))
363           .getId();
364       Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
365
366       validationVsp = new ItemCreationDto();
367       validationVsp.setItemId(validationVspId);
368       validationVsp
369           .setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
370
371       return Response.ok(validationVsp).build();
372     }
373   }
374
375   @Override
376   public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
377     byte[] orchestrationTemplateFile =
378         vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
379
380     if (orchestrationTemplateFile == null) {
381       return Response.status(Response.Status.NOT_FOUND).build();
382     }
383     Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
384     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
385     return response.build();
386   }
387
388   @Override
389   public Response listPackages(String category, String subCategory, String user) {
390     List<PackageInfo> packageInfoList =
391         vendorSoftwareProductManager.listPackages(category, subCategory);
392
393     GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
394     MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
395
396     if (packageInfoList != null) {
397       for (PackageInfo packageInfo : packageInfoList) {
398         results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
399       }
400     }
401     return Response.ok(results).build();
402   }
403
404   @Override
405   public Response getTranslatedFile(String vspId, String versionName, String user) {
406     List<Version> versions = versioningManager.list(vspId);
407     Version version;
408     if (versionName == null) {
409       version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
410           .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
411           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
412     } else {
413       version = versions.stream().filter(ver -> versionName.equals(ver.getName()))
414           .findFirst()
415           .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
416
417       if (version.getStatus() != VersionStatus.Certified) {
418         throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
419       }
420     }
421
422     File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
423
424     Response.ResponseBuilder response = Response.ok(zipFile);
425     if (zipFile == null) {
426       return Response.status(Response.Status.NOT_FOUND).build();
427     }
428     response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
429
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
501       activityLogManager.logActivity(
502           new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false,
503               "Failed on validation before submit", ""));
504       return Optional.of(validationResponse);
505     }
506
507     versioningManager.submit(vspId, version, message);
508
509     activityLogManager.logActivity(
510         new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
511     return Optional.empty();
512   }
513
514   private void notifyUsers(String itemId, String itemName, Version version, String message,
515                            String userName, NotificationEventTypes eventType) {
516     Map<String, Object> eventProperties = new HashMap<>();
517     eventProperties
518         .put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
519     eventProperties.put(ITEM_ID, itemId);
520
521     if (version != null) {
522       eventProperties.put(VERSION_NAME, version.getName() == null
523           ? versioningManager.get(itemId, version).getName()
524           : version.getName());
525       eventProperties.put(VERSION_ID, version.getId());
526     }
527
528     eventProperties.put(SUBMIT_DESCRIPTION, message);
529     eventProperties.put(PERMISSION_USER, userName);
530
531     Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
532     try {
533       notifier.notifySubscribers(syncEvent, userName);
534     } catch (Exception e) {
535       LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId);
536     }
537   }
538
539   private class SyncEvent implements Event {
540
541     private final String eventType;
542     private final String originatorId;
543     private final Map<String, Object> attributes;
544     private final String entityId;
545
546     SyncEvent(String eventType, String originatorId,
547               Map<String, Object> attributes, String entityId) {
548       this.eventType = eventType;
549       this.originatorId = originatorId;
550       this.attributes = attributes;
551       this.entityId = entityId;
552     }
553
554     @Override
555     public String getEventType() {
556       return eventType;
557     }
558
559     @Override
560     public String getOriginatorId() {
561       return originatorId;
562     }
563
564     @Override
565     public Map<String, Object> getAttributes() {
566       return attributes;
567     }
568
569     @Override
570     public String getEntityId() {
571       return entityId;
572     }
573   }
574
575   private Response createPackage(String vspId, Version version) throws IOException {
576     Version retrievedVersion = versioningManager.get(vspId, version);
577     if (retrievedVersion.getStatus() != VersionStatus.Certified) {
578       throw new CoreException(
579           new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
580               .build());
581     }
582     PackageInfo packageInfo =
583         vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
584     return Response.ok(packageInfo == null
585         ? null
586         : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class))
587         .build();
588   }
589
590   private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
591     OrchestrationTemplateCandidateData candidateInfo =
592         OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
593             .getInfo(vspId, version);
594     if (Objects.nonNull(candidateInfo) && Objects.nonNull(candidateInfo.getFileSuffix())) {
595       vspDetailsDto.setValidationData(candidateInfo.getValidationDataStructure());
596       vspDetailsDto.setNetworkPackageName(candidateInfo.getFileName());
597       vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.getFileSuffix());
598     } else {
599       OrchestrationTemplateEntity orchestrationTemplateInfo =
600           vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
601       if (Objects.nonNull(orchestrationTemplateInfo)) {
602         vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
603         vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
604         vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
605       }
606     }
607   }
608
609   private boolean userHasPermission(String itemId, String userId) {
610     String permission = permissionsManager.getUserItemPermiission(itemId, userId);
611     return permission != null && permission
612         .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name());
613   }
614 }