16ef8c5761c36a6fb0643d2417999b366fca9da5
[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             if (vspDetails.getVlmVersion() != null) {
251                 // sync vlm if not exists on user space
252                 versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
253             }
254
255             Optional<ValidationResponse> validationResponse =
256                     submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user);
257             // TODO: 8/9/2017 before collaboration checkout was done at this scenario (equivalent
258             // to new version in collaboration). need to decide what should be done now.
259             validationResponse.ifPresent(validationResponse1 -> {
260                 throw new IllegalStateException("Certified vsp after healing failed on validation");
261             });
262             vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
263         } catch (Exception ex) {
264             LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(),
265                     baseVersionId), ex);
266         }
267     }
268
269     @Override
270     public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto,
271                               String user) {
272         VspDetails vspDetails =
273                 new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
274         vspDetails.setId(vspId);
275         vspDetails.setVersion(new Version(versionId));
276
277         vendorSoftwareProductManager.updateVsp(vspDetails);
278
279         return Response.ok().build();
280     }
281
282     @Override
283     public Response deleteVsp(String vspId, String user) {
284         Item vsp = itemManager.get(vspId);
285
286         if (!vsp.getType().equals(ItemType.vsp.name())) {
287             throw new CoreException((new ErrorCode.ErrorCodeBuilder()
288                     .withMessage(String.format("Vsp with id %s does not exist.",
289                             vspId)).build()));
290         }
291
292         Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
293         if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) {
294             versioningManager.list(vspId)
295                     .forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
296             itemManager.delete(vsp);
297             permissionsManager.deleteItemPermissions(vspId);
298             uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
299             notifyUsers(vspId, vsp.getName(), null, null, user,
300                     NotificationEventTypes.DELETE);
301
302             return Response.ok().build();
303         } else {
304             return Response.status(Response.Status.FORBIDDEN)
305                     .entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build();
306         }
307     }
308
309     @Override
310     public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request,
311                                                String vspId, String versionId,
312                                                String user) throws IOException {
313         Version version = new Version(versionId);
314
315         if (request.getAction() == VendorSoftwareProductAction.Submit) {
316             if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
317                 return Response.status(Response.Status.FORBIDDEN)
318                         .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
319             }
320             String message = request.getSubmitRequest() == null ? "Submit"
321                     : request.getSubmitRequest().getMessage();
322             Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
323
324             if (validationResponse.isPresent()) {
325                 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
326                         .applyMapping(validationResponse.get(), ValidationResponseDto.class);
327                 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto)
328                         .build();
329             }
330
331             notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
332
333         } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
334             return createPackage(vspId, version);
335         }
336
337         return Response.ok().build();
338     }
339
340     @Override
341     public Response getValidationVsp(String user) {
342         ItemCreationDto validationVsp = retrieveValidationVsp();
343         return Response.ok(validationVsp).build();
344     }
345
346     private ItemCreationDto retrieveValidationVsp() {
347
348         synchronized (VALIDATION_VSP_CACHE_LOCK) {
349
350             if (cachedValidationVsp != null) {
351                 return cachedValidationVsp;
352             }
353
354             VspRequestDto validationVspRequest = new VspRequestDto();
355             validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
356             validationVspRequest.setName(VALIDATION_VSP_NAME);
357
358             try {
359
360                 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
361                 return cachedValidationVsp;
362
363             } catch (CoreException vspCreateException) {
364                 LOGGER.debug("Failed to create validation VSP", vspCreateException);
365                 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType())
366                         && VALIDATION_VSP_NAME.equals(item.getName());
367                 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst()
368                         .orElseThrow(() -> new IllegalStateException(
369                                 "Vsp with name " + VALIDATION_VSP_NAME +
370                                 " does not exist even though the name exists according to " +
371                                 "unique value util"))
372                         .getId();
373
374                 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
375
376                 cachedValidationVsp = new ItemCreationDto();
377                 cachedValidationVsp.setItemId(validationVspId);
378                 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
379                 return cachedValidationVsp;
380             }
381         }
382     }
383
384     @Override
385     public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
386         byte[] orchestrationTemplateFile =
387                 vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
388
389         if (orchestrationTemplateFile == null) {
390             return Response.status(Response.Status.NOT_FOUND).build();
391         }
392         Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
393         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
394         return response.build();
395     }
396
397     @Override
398     public Response listPackages(String status, String category, String subCategory, String user) {
399
400         List<String> vspsIds =
401                 getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user)
402                         .stream().map(Item::getId).collect(Collectors.toList());
403
404         List<PackageInfo> packageInfoList =
405                 vendorSoftwareProductManager.listPackages(category, subCategory);
406
407         packageInfoList = packageInfoList.stream().
408                 filter(packageInfo -> vspsIds.contains(packageInfo.getVspId()))
409                 .collect(Collectors.toList());
410
411         GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
412         MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
413
414         if (packageInfoList != null) {
415             for (PackageInfo packageInfo : packageInfoList) {
416                 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
417             }
418         }
419         return Response.ok(results).build();
420     }
421
422     @Override
423     public Response getTranslatedFile(String vspId, String versionName, String user) {
424         List<Version> versions = versioningManager.list(vspId);
425         Version version;
426         if (versionName == null) {
427             version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
428                     .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
429                     .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
430         } else {
431             version = versions.stream().filter(ver -> versionName.equals(ver.getName()))
432                     .findFirst()
433                     .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
434
435             if (version.getStatus() != VersionStatus.Certified) {
436                 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
437             }
438         }
439
440         File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
441
442         Response.ResponseBuilder response = Response.ok(zipFile);
443         if (zipFile == null) {
444             return Response.status(Response.Status.NOT_FOUND).build();
445         }
446         response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
447
448         return response.build();
449     }
450
451     @Override
452     public Response getQuestionnaire(String vspId, String versionId, String user) {
453         QuestionnaireResponse questionnaireResponse =
454                 vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
455
456         if (questionnaireResponse.getErrorMessage() != null) {
457             return Response.status(Response.Status.EXPECTATION_FAILED).entity(
458                     new MapQuestionnaireResponseToQuestionnaireResponseDto()
459                             .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build();
460         }
461
462         QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
463                 .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
464         return Response.ok(result).build();
465     }
466
467     @Override
468     public Response updateQuestionnaire(String questionnaireData, String vspId, String
469             versionId, String user) {
470         vendorSoftwareProductManager
471                 .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
472         return Response.ok().build();
473     }
474
475     @Override
476     public Response heal(String vspId, String versionId, String user) {
477         HealingManagerFactory.getInstance().createInterface()
478                 .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
479         return Response.ok().build();
480     }
481
482     @Override
483     public Response getVspInformationArtifact(String vspId, String versionId, String user) {
484         File textInformationArtifact =
485                 vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
486
487         Response.ResponseBuilder response = Response.ok(textInformationArtifact);
488         if (textInformationArtifact == null) {
489             return Response.status(Response.Status.NOT_FOUND).build();
490         }
491         response
492                 .header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
493         return response.build();
494     }
495
496     @Override
497     public Response listComputes(String vspId, String version, String user) {
498
499         Collection<ComputeEntity> computes =
500                 vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
501
502         MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
503         GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
504         for (ComputeEntity compute : computes) {
505             results.add(mapper.applyMapping(compute, VspComputeDto.class));
506         }
507
508         return Response.ok(results).build();
509     }
510
511     private Optional<ValidationResponse> submit(String vspId, Version version, String message,
512                                                 String user) throws IOException {
513
514         ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspId, version);
515         Map<String, List<ErrorMessage>> compilationErrors =
516                 vendorSoftwareProductManager.compile(vspId, version);
517         if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
518
519             activityLogManager.logActivity(
520                     new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false,
521                             "Failed on validation before submit", ""));
522             return Optional.of(validationResponse);
523         }
524
525         versioningManager.submit(vspId, version, message);
526
527         activityLogManager.logActivity(
528                 new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
529         return Optional.empty();
530     }
531
532     private void notifyUsers(String itemId, String itemName, Version version, String message,
533                              String userName, NotificationEventTypes eventType) {
534         Map<String, Object> eventProperties = new HashMap<>();
535         eventProperties
536                 .put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
537         eventProperties.put(ITEM_ID, itemId);
538
539         if (version != null) {
540             eventProperties.put(VERSION_NAME, version.getName() == null
541                     ? versioningManager.get(itemId, version).getName()
542                     : version.getName());
543             eventProperties.put(VERSION_ID, version.getId());
544         }
545
546         eventProperties.put(SUBMIT_DESCRIPTION, message);
547         eventProperties.put(PERMISSION_USER, userName);
548
549         Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
550         try {
551             notifier.notifySubscribers(syncEvent, userName);
552         } catch (Exception e) {
553             LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
554         }
555     }
556
557     private Response createPackage(String vspId, Version version) throws IOException {
558         Version retrievedVersion = versioningManager.get(vspId, version);
559         if (retrievedVersion.getStatus() != VersionStatus.Certified) {
560             throw new CoreException(
561                     new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version)
562                             .build());
563         }
564         PackageInfo packageInfo =
565                 vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
566         return Response.ok(packageInfo == null
567                 ? null
568                 : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class))
569                 .build();
570     }
571
572     private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
573         OrchestrationTemplateCandidateData candidateInfo =
574                 OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
575                         .getInfo(vspId, version);
576         if (Objects.nonNull(candidateInfo) && Objects.nonNull(candidateInfo.getFileSuffix())) {
577             vspDetailsDto.setValidationData(candidateInfo.getValidationDataStructure());
578             vspDetailsDto.setNetworkPackageName(candidateInfo.getFileName());
579             vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.getFileSuffix());
580         } else {
581             OrchestrationTemplateEntity orchestrationTemplateInfo =
582                     vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
583             if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo
584                     .getFileSuffix())) {
585                 vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
586                 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
587                 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
588             }
589         }
590     }
591
592     private boolean userHasPermission(String itemId, String userId) {
593     String permission = permissionsManager.getUserItemPermission(itemId, userId);
594         return permission != null && permission
595                 .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name());
596     }
597
598     private Predicate<Item> createItemPredicate(String versionStatus,
599                                                 String itemStatus,
600                                                 String user) {
601         Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
602
603         if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
604             itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
605         } else {
606             itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
607
608             if (VersionStatus.Certified.name().equals(versionStatus)) {
609                 itemPredicate = itemPredicate
610                         .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
611
612             } else if (VersionStatus.Draft.name().equals(versionStatus)) {
613                 itemPredicate = itemPredicate.and(
614                         item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft)
615                                 && userHasPermission(item.getId(), user));
616             }
617         }
618         return itemPredicate;
619     }
620
621     private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
622
623         Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
624
625         return itemManager.list(itemPredicate).stream()
626                 .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())).
627                         collect(Collectors.toList());
628     }
629
630     private class SyncEvent implements Event {
631
632         private final String eventType;
633
634         private final String originatorId;
635         private final Map<String, Object> attributes;
636         private final String entityId;
637
638         SyncEvent(String eventType, String originatorId,
639                   Map<String, Object> attributes, String entityId) {
640             this.eventType = eventType;
641             this.originatorId = originatorId;
642             this.attributes = attributes;
643             this.entityId = entityId;
644         }
645
646         @Override
647         public String getEventType() {
648             return eventType;
649         }
650
651         @Override
652         public String getOriginatorId() {
653             return originatorId;
654         }
655
656         @Override
657         public Map<String, Object> getAttributes() {
658             return attributes;
659         }
660
661         @Override
662         public String getEntityId() {
663             return entityId;
664         }
665     }
666 }