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