2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.openecomp.sdcrests.vsp.rest.services;
18 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
19 import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER;
20 import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME;
21 import static org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod.NetworkPackage;
22 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID;
23 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME;
24 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION;
25 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID;
26 import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME;
29 import java.io.IOException;
30 import java.util.Collection;
31 import java.util.Comparator;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.List;
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.be.csar.storage.ArtifactStorageManager;
50 import org.openecomp.sdc.be.csar.storage.StorageFactory;
51 import org.openecomp.sdc.common.errors.CoreException;
52 import org.openecomp.sdc.common.errors.ErrorCode;
53 import org.openecomp.sdc.common.errors.Messages;
54 import org.openecomp.sdc.datatypes.error.ErrorMessage;
55 import org.openecomp.sdc.datatypes.model.ItemType;
56 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
57 import org.openecomp.sdc.itempermissions.PermissionsManager;
58 import org.openecomp.sdc.itempermissions.PermissionsManagerFactory;
59 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
60 import org.openecomp.sdc.logging.api.Logger;
61 import org.openecomp.sdc.logging.api.LoggerFactory;
62 import org.openecomp.sdc.notification.dtos.Event;
63 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
64 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
65 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
66 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
67 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
68 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
69 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
70 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
71 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
73 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
74 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
75 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
76 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
77 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
78 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
79 import org.openecomp.sdc.versioning.AsdcItemManager;
80 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
81 import org.openecomp.sdc.versioning.VersioningManager;
82 import org.openecomp.sdc.versioning.VersioningManagerFactory;
83 import org.openecomp.sdc.versioning.dao.types.Version;
84 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
85 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
86 import org.openecomp.sdc.versioning.types.Item;
87 import org.openecomp.sdc.versioning.types.ItemStatus;
88 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
89 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
90 import org.openecomp.sdcrests.item.types.ItemCreationDto;
91 import org.openecomp.sdcrests.item.types.VersionDto;
92 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
93 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
94 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
95 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
96 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
97 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
98 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
99 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
100 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
101 import org.openecomp.sdcrests.vsp.rest.CatalogVspClient;
102 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
103 import org.openecomp.sdcrests.vsp.rest.exception.VendorSoftwareProductsExceptionSupplier;
104 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
105 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
106 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
107 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
108 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
109 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
110 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
111 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
112 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
113 import org.springframework.context.annotation.Scope;
114 import org.springframework.stereotype.Service;
117 @Service("vendorSoftwareProducts")
118 @Scope(value = "prototype")
119 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
121 private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
122 private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
123 private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
124 private static final String ATTACHMENT_FILENAME = "attachment; filename=";
125 private static final String SUBMIT_HEALED_VERSION_ERROR = "VSP Id %s: Error while submitting version %s created based on Certified version %s for healing purpose.";
126 private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
127 private static final Object VALIDATION_VSP_CACHE_LOCK = new Object();
128 private static ItemCreationDto cachedValidationVsp;
129 private final AsdcItemManager itemManager;
130 private final PermissionsManager permissionsManager;
131 private final VersioningManager versioningManager;
132 private final VendorSoftwareProductManager vendorSoftwareProductManager;
133 private final ActivityLogManager activityLogManager;
134 private final NotificationPropagationManager notifier;
135 private final UniqueValueUtil uniqueValueUtil;
136 private final StorageFactory storageFactory;
137 private final CatalogVspClient catalogVspClient;
139 public VendorSoftwareProductsImpl() {
140 this.itemManager = AsdcItemManagerFactory.getInstance().createInterface();
141 this.permissionsManager = PermissionsManagerFactory.getInstance().createInterface();
142 this.versioningManager = VersioningManagerFactory.getInstance().createInterface();
143 this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
144 this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
145 this.notifier = NotificationPropagationManagerFactory.getInstance().createInterface();
146 this.uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface());
147 this.storageFactory = new StorageFactory();
148 this.catalogVspClient = new CatalogVspClientImpl();
151 public VendorSoftwareProductsImpl(AsdcItemManager itemManager,
152 PermissionsManager permissionsManager,
153 VersioningManager versioningManager,
154 VendorSoftwareProductManager vendorSoftwareProductManager,
155 ActivityLogManager activityLogManager,
156 NotificationPropagationManager notifier,
157 UniqueValueUtil uniqueValueUtil,
158 final StorageFactory storageFactory,
159 CatalogVspClient catalogVspClient) {
160 this.itemManager = itemManager;
161 this.permissionsManager = permissionsManager;
162 this.versioningManager = versioningManager;
163 this.vendorSoftwareProductManager = vendorSoftwareProductManager;
164 this.activityLogManager = activityLogManager;
165 this.notifier = notifier;
166 this.uniqueValueUtil = uniqueValueUtil;
167 this.storageFactory = storageFactory;
168 this.catalogVspClient = catalogVspClient;
172 public Response createVsp(VspRequestDto vspRequestDto, String user) {
173 ItemCreationDto vspCreationDto = createVspItem(vspRequestDto, user);
174 return Response.ok(vspCreationDto).build();
177 private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) {
178 OnboardingMethod onboardingMethod = null;
180 onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
181 } catch (IllegalArgumentException e) {
182 LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
183 throwUnknownOnboardingMethodException(e);
185 ItemCreationDto itemCreationDto = null;
186 if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) {
187 itemCreationDto = createItem(vspRequestDto, user, onboardingMethod);
189 throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
191 return itemCreationDto;
194 private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) {
195 Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
196 item.setType(ItemType.vsp.name());
198 item.setStatus(ItemStatus.ACTIVE);
199 item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
200 uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
201 item = itemManager.create(item);
202 uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
203 Version version = versioningManager.create(item.getId(), new Version(), null);
204 VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
205 vspDetails.setId(item.getId());
206 vspDetails.setVersion(version);
207 vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
208 vendorSoftwareProductManager.createVsp(vspDetails);
209 versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
210 ItemCreationDto itemCreationDto = new ItemCreationDto();
211 itemCreationDto.setItemId(item.getId());
212 itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
213 activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", ""));
214 return itemCreationDto;
217 private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
218 ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder();
219 throw new CoreException(onboardingMethodUpdateErrorCode, e);
223 public Response listVsps(String versionStatus, String itemStatus, String user) {
224 GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
225 MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
226 getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
227 return Response.ok(results).build();
231 public Response getVsp(String vspId, String versionId, String user) {
232 Version version = versioningManager.get(vspId, new Version(versionId));
233 VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
235 HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> {
236 vspDetails.setVersion(healedVersion);
237 if (version.getStatus() == VersionStatus.Certified) {
238 submitHealedVersion(vspDetails, versionId, user);
241 } catch (Exception e) {
242 LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e);
244 VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
245 addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto);
246 return Response.ok(vspDetailsDto).build();
250 public Response getLatestVsp(final String vspId, final String user) {
251 final List<Version> versions = versioningManager.list(vspId);
252 final Version version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
253 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
254 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
255 return getVsp(vspId, version.getId(), user);
258 private void submitHealedVersion(VspDetails vspDetails, String baseVersionId, String user) {
260 if (vspDetails.getVlmVersion() != null) {
261 // sync vlm if not exists on user space
262 versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
264 submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> {
265 throw new IllegalStateException("Certified vsp after healing failed on validation");
267 vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
268 } catch (Exception ex) {
269 LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex);
274 public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) {
275 VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
276 vspDetails.setId(vspId);
277 vspDetails.setVersion(new Version(versionId));
278 vendorSoftwareProductManager.updateVsp(vspDetails);
279 updateVspItem(vspId, vspDescriptionDto);
280 return Response.ok().build();
284 public Response deleteVsp(final String vspId, final String user) {
285 final Item vsp = itemManager.get(vspId);
286 if (!ItemType.vsp.getName().equals(vsp.getType())) {
287 throw VendorSoftwareProductsExceptionSupplier.vspNotFound(vspId).get();
290 checkIfCanDeleteVsp(vsp, user);
293 deleteVspFromStorage(vspId, user);
294 } catch (final Exception e) {
295 logDeleteFromStorageFailure(vspId, user);
296 throw VendorSoftwareProductsExceptionSupplier.deleteVspFromStorageFailure(vspId).get();
300 deleteVsp(vspId, user, vsp);
301 } catch (final Exception e) {
302 throw VendorSoftwareProductsExceptionSupplier.deleteVspFromDatabaseFailure(vspId).get();
305 return Response.ok().build();
308 private void checkIfCanDeleteVsp(final Item vsp, final String user) {
309 final String vspId = vsp.getId();
311 checkIfVspInUse(user, vspId);
313 if (isVspItemNeverCertified(vsp)) {
316 if (!isVspItemArchived(vspId, user)) {
317 throw VendorSoftwareProductsExceptionSupplier.deleteNotArchivedVsp(vspId).get();
321 private void checkIfVspInUse(final String user, final String vspId) {
322 final Optional<String> vfNameThatUsesVspOpt;
324 vfNameThatUsesVspOpt = catalogVspClient.findNameOfVfUsingVsp(vspId, user);
325 } catch (final Exception e) {
326 throw VendorSoftwareProductsExceptionSupplier.deleteGenericError(vspId).get();
328 if (vfNameThatUsesVspOpt.isPresent()) {
329 final String vfName = vfNameThatUsesVspOpt.get();
330 throw VendorSoftwareProductsExceptionSupplier.vspInUseByVf(vfName).get();
334 private boolean isVspItemArchived(final String vspId, final String user) {
335 return getVspList(null, ItemStatus.ARCHIVED.name(), user).stream().anyMatch(item -> vspId.equals(item.getId()));
338 private boolean isVspItemNeverCertified(final Item vsp) {
339 final Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
340 return certifiedVersionsCounter == null || certifiedVersionsCounter == 0;
343 private void deleteVspFromStorage(final String vspId, final String user) {
344 final ArtifactStorageManager artifactStorageManager = storageFactory.createArtifactStorageManager();
345 if (artifactStorageManager.isEnabled()) {
346 artifactStorageManager.delete(vspId);
347 logDeleteFromStorageAllSuccess(vspId, user);
351 private void logDeleteFromStorageFailure(final String vspId, final String user) {
352 final String message = Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId);
354 versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
355 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, false, message, message)
357 } catch (final Exception e) {
358 LOGGER.error("Could not log activity '{}'", message, e);
361 private void logDeleteFromStorageAllSuccess(final String vspId, final String user) {
362 final String message = String.format("VSP '%s' fully deleted from the storage", vspId);
364 versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
365 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, true, message, message)
367 } catch (final Exception e) {
368 LOGGER.error("Could not log activity '{}'", message, e);
372 private void deleteVsp(final String vspId, final String user, final Item vsp) {
373 versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
374 itemManager.delete(vsp);
375 permissionsManager.deleteItemPermissions(vspId);
376 uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
377 notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
381 public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
383 Version version = new Version(versionId);
384 if (request.getAction() == VendorSoftwareProductAction.Submit) {
385 if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
386 return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
388 String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
389 Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
390 if (validationResponse.isPresent()) {
391 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
392 .applyMapping(validationResponse.get(), ValidationResponseDto.class);
393 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
395 notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
396 } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
397 return createPackage(vspId, version);
399 return Response.ok().build();
403 public Response getValidationVsp(String user) {
404 ItemCreationDto validationVsp = retrieveValidationVsp();
405 return Response.ok(validationVsp).build();
408 private ItemCreationDto retrieveValidationVsp() {
409 synchronized (VALIDATION_VSP_CACHE_LOCK) {
410 if (cachedValidationVsp != null) {
411 return cachedValidationVsp;
413 VspRequestDto validationVspRequest = new VspRequestDto();
414 validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
415 validationVspRequest.setName(VALIDATION_VSP_NAME);
417 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
418 return cachedValidationVsp;
419 } catch (CoreException vspCreateException) {
420 LOGGER.debug("Failed to create validation VSP", vspCreateException);
421 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
422 .equals(item.getName());
423 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
424 "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
426 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
427 cachedValidationVsp = new ItemCreationDto();
428 cachedValidationVsp.setItemId(validationVspId);
429 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
430 return cachedValidationVsp;
436 public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
437 byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
438 if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
439 return Response.status(Response.Status.NOT_FOUND).build();
441 Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
442 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
443 return response.build();
447 public Response listPackages(String status, String category, String subCategory, String user) {
448 List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
449 .collect(Collectors.toList());
450 List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
451 packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
452 GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
453 MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
454 if (packageInfoList != null) {
455 for (PackageInfo packageInfo : packageInfoList) {
456 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
459 return Response.ok(results).build();
463 public Response getTranslatedFile(String vspId, String versionId, String user) {
464 final List<Version> versions = versioningManager.list(vspId);
465 final Version version;
466 if (versionId == null) {
467 version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
468 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
469 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
471 version = versions.stream()
472 .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
474 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
475 if (version.getStatus() != VersionStatus.Certified) {
476 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
479 File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
480 Response.ResponseBuilder response = Response.ok(zipFile);
481 if (zipFile == null) {
482 return Response.status(Response.Status.NOT_FOUND).build();
484 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
485 return response.build();
489 public Response getQuestionnaire(String vspId, String versionId, String user) {
490 QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
491 if (questionnaireResponse.getErrorMessage() != null) {
492 return Response.status(Response.Status.EXPECTATION_FAILED)
493 .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
496 QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
497 .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
498 return Response.ok(result).build();
502 public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
503 vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
504 return Response.ok().build();
508 public Response heal(String vspId, String versionId, String user) {
509 HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
510 return Response.ok().build();
514 public Response getVspInformationArtifact(String vspId, String versionId, String user) {
515 File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
516 Response.ResponseBuilder response = Response.ok(textInformationArtifact);
517 if (textInformationArtifact == null) {
518 return Response.status(Response.Status.NOT_FOUND).build();
520 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
521 return response.build();
525 public Response listComputes(String vspId, String version, String user) {
526 Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
527 MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
528 GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
529 for (ComputeEntity compute : computes) {
530 results.add(mapper.applyMapping(compute, VspComputeDto.class));
532 return Response.ok(results).build();
535 private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
536 Item retrievedItem = itemManager.get(vspId);
537 Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
539 item.setType(retrievedItem.getType());
540 item.setOwner(retrievedItem.getOwner());
541 item.setStatus(retrievedItem.getStatus());
542 item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
543 item.setCreationTime(retrievedItem.getCreationTime());
544 item.setModificationTime(new Date());
545 item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
546 itemManager.update(item);
549 private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
550 VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
551 if (vspDetails.getVlmVersion() != null) {
552 vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
554 ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
555 Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
556 if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
558 .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
559 return Optional.of(validationResponse);
561 versioningManager.submit(vspId, version, message);
562 activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
563 return Optional.empty();
566 private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
567 Map<String, Object> eventProperties = new HashMap<>();
568 eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
569 eventProperties.put(ITEM_ID, itemId);
570 if (version != null) {
571 eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
572 eventProperties.put(VERSION_ID, version.getId());
574 eventProperties.put(SUBMIT_DESCRIPTION, message);
575 eventProperties.put(PERMISSION_USER, userName);
576 Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
578 notifier.notifySubscribers(syncEvent, userName);
579 } catch (Exception e) {
580 LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
584 private Response createPackage(String vspId, Version version) throws IOException {
585 Version retrievedVersion = versioningManager.get(vspId, version);
586 if (retrievedVersion.getStatus() != VersionStatus.Certified) {
587 throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
589 PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
590 return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
593 private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
594 Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
595 .getInfo(vspId, version);
596 if (candidateInfo.isPresent()) {
597 if (candidateInfo.get().getValidationDataStructure() != null) {
598 vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
600 vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
601 vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
603 OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
604 if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
605 if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
606 vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
608 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
609 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
614 private boolean userHasPermission(String itemId, String userId) {
615 return permissionsManager.getUserItemPermission(itemId, userId)
616 .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
619 private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
620 Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
621 if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
622 itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
624 itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
625 if (VersionStatus.Certified.name().equals(versionStatus)) {
626 itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
627 } else if (VersionStatus.Draft.name().equals(versionStatus)) {
628 itemPredicate = itemPredicate
629 .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
632 return itemPredicate;
635 private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
636 Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
637 return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
638 .collect(Collectors.toList());
641 private class SyncEvent implements Event {
643 private final String eventType;
644 private final String originatorId;
645 private final Map<String, Object> attributes;
646 private final String entityId;
648 SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
649 this.eventType = eventType;
650 this.originatorId = originatorId;
651 this.attributes = attributes;
652 this.entityId = entityId;
656 public String getEventType() {
661 public String getOriginatorId() {
666 public Map<String, Object> getAttributes() {
671 public String getEntityId() {