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.nio.ByteBuffer;
31 import java.util.Collection;
32 import java.util.Comparator;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.ArrayList;
40 import java.util.Objects;
41 import java.util.Optional;
42 import java.util.function.Predicate;
43 import java.util.stream.Collectors;
44 import javax.inject.Named;
45 import javax.ws.rs.core.Response;
46 import org.apache.commons.collections4.MapUtils;
47 import org.openecomp.core.dao.UniqueValueDaoFactory;
48 import org.openecomp.core.util.UniqueValueUtil;
49 import org.openecomp.sdc.activitylog.ActivityLogManager;
50 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
51 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
52 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
53 import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
54 import org.openecomp.sdc.be.csar.storage.StorageFactory;
55 import org.openecomp.sdc.common.errors.CoreException;
56 import org.openecomp.sdc.common.errors.ErrorCode;
57 import org.openecomp.sdc.common.errors.Messages;
58 import org.openecomp.sdc.datatypes.error.ErrorMessage;
59 import org.openecomp.sdc.datatypes.model.ItemType;
60 import org.openecomp.sdc.healing.factory.HealingManagerFactory;
61 import org.openecomp.sdc.itempermissions.PermissionsManager;
62 import org.openecomp.sdc.itempermissions.PermissionsManagerFactory;
63 import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
64 import org.openecomp.sdc.logging.api.Logger;
65 import org.openecomp.sdc.logging.api.LoggerFactory;
66 import org.openecomp.sdc.notification.dtos.Event;
67 import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory;
68 import org.openecomp.sdc.notification.services.NotificationPropagationManager;
69 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
70 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
71 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
72 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity;
73 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod;
74 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
75 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
76 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo;
77 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
78 import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder;
79 import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder;
80 import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder;
81 import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse;
82 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
83 import org.openecomp.sdc.versioning.AsdcItemManager;
84 import org.openecomp.sdc.versioning.AsdcItemManagerFactory;
85 import org.openecomp.sdc.versioning.VersioningManager;
86 import org.openecomp.sdc.versioning.VersioningManagerFactory;
87 import org.openecomp.sdc.versioning.dao.types.Version;
88 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
89 import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder;
90 import org.openecomp.sdc.versioning.types.Item;
91 import org.openecomp.sdc.versioning.types.ItemStatus;
92 import org.openecomp.sdc.versioning.types.NotificationEventTypes;
93 import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto;
94 import org.openecomp.sdcrests.item.types.ItemCreationDto;
95 import org.openecomp.sdcrests.item.types.VersionDto;
96 import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto;
97 import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto;
98 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
99 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VendorSoftwareProductAction;
100 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto;
101 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto;
102 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto;
103 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto;
104 import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto;
105 import org.openecomp.sdcrests.vsp.rest.CatalogVspClient;
106 import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts;
107 import org.openecomp.sdcrests.vsp.rest.exception.VendorSoftwareProductsExceptionSupplier;
108 import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto;
109 import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto;
110 import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto;
111 import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto;
112 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
113 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem;
114 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails;
115 import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto;
116 import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper;
117 import org.springframework.context.annotation.Scope;
118 import org.springframework.stereotype.Service;
121 @Service("vendorSoftwareProducts")
122 @Scope(value = "prototype")
123 public class VendorSoftwareProductsImpl implements VendorSoftwareProducts {
125 private static final String VALIDATION_VSP_NAME = "validationOnlyVspName";
126 private static final String VALIDATION_VSP_USER = "validationOnlyVspUser";
127 private static final String SUBMIT_ITEM_ACTION = "Submit_Item";
128 private static final String ATTACHMENT_FILENAME = "attachment; filename=";
129 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.";
130 private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class);
131 private static final Object VALIDATION_VSP_CACHE_LOCK = new Object();
132 private static ItemCreationDto cachedValidationVsp;
133 private final AsdcItemManager itemManager;
134 private final PermissionsManager permissionsManager;
135 private final VersioningManager versioningManager;
136 private final VendorSoftwareProductManager vendorSoftwareProductManager;
137 private final ActivityLogManager activityLogManager;
138 private final NotificationPropagationManager notifier;
139 private final UniqueValueUtil uniqueValueUtil;
140 private final StorageFactory storageFactory;
141 private final CatalogVspClient catalogVspClient;
143 public VendorSoftwareProductsImpl() {
144 this.itemManager = AsdcItemManagerFactory.getInstance().createInterface();
145 this.permissionsManager = PermissionsManagerFactory.getInstance().createInterface();
146 this.versioningManager = VersioningManagerFactory.getInstance().createInterface();
147 this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
148 this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
149 this.notifier = NotificationPropagationManagerFactory.getInstance().createInterface();
150 this.uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface());
151 this.storageFactory = new StorageFactory();
152 this.catalogVspClient = new CatalogVspClientImpl();
155 public VendorSoftwareProductsImpl(AsdcItemManager itemManager,
156 PermissionsManager permissionsManager,
157 VersioningManager versioningManager,
158 VendorSoftwareProductManager vendorSoftwareProductManager,
159 ActivityLogManager activityLogManager,
160 NotificationPropagationManager notifier,
161 UniqueValueUtil uniqueValueUtil,
162 final StorageFactory storageFactory,
163 CatalogVspClient catalogVspClient) {
164 this.itemManager = itemManager;
165 this.permissionsManager = permissionsManager;
166 this.versioningManager = versioningManager;
167 this.vendorSoftwareProductManager = vendorSoftwareProductManager;
168 this.activityLogManager = activityLogManager;
169 this.notifier = notifier;
170 this.uniqueValueUtil = uniqueValueUtil;
171 this.storageFactory = storageFactory;
172 this.catalogVspClient = catalogVspClient;
176 public Response createVsp(VspRequestDto vspRequestDto, String user) {
177 ItemCreationDto vspCreationDto = createVspItem(vspRequestDto, user);
178 return Response.ok(vspCreationDto).build();
181 private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) {
182 OnboardingMethod onboardingMethod = null;
184 onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod());
185 } catch (IllegalArgumentException e) {
186 LOGGER.error("Error while creating VSP. Message: " + e.getMessage());
187 throwUnknownOnboardingMethodException(e);
189 ItemCreationDto itemCreationDto = null;
190 if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) {
191 itemCreationDto = createItem(vspRequestDto, user, onboardingMethod);
193 throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method"));
195 return itemCreationDto;
198 private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) {
199 Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class);
200 item.setType(ItemType.vsp.name());
202 item.setStatus(ItemStatus.ACTIVE);
203 item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name());
204 uniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
205 item = itemManager.create(item);
206 uniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName());
207 Version version = versioningManager.create(item.getId(), new Version(), null);
208 VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class);
209 vspDetails.setId(item.getId());
210 vspDetails.setVersion(version);
211 vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod());
212 vendorSoftwareProductManager.createVsp(vspDetails);
213 versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName());
214 ItemCreationDto itemCreationDto = new ItemCreationDto();
215 itemCreationDto.setItemId(item.getId());
216 itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class));
217 activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", ""));
218 return itemCreationDto;
221 private void throwUnknownOnboardingMethodException(IllegalArgumentException e) {
222 ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder();
223 throw new CoreException(onboardingMethodUpdateErrorCode, e);
227 public Response listVsps(String versionStatus, String itemStatus, String user) {
228 GenericCollectionWrapper<VspDetailsDto> results = new GenericCollectionWrapper<>();
229 MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto();
230 getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class)));
231 return Response.ok(results).build();
235 public Response getVsp(String vspId, String versionId, String user) {
236 Version version = versioningManager.get(vspId, new Version(versionId));
237 VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
239 HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> {
240 vspDetails.setVersion(healedVersion);
241 if (version.getStatus() == VersionStatus.Certified) {
242 submitHealedVersion(vspDetails, versionId, user);
245 } catch (Exception e) {
246 LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e);
248 VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class);
249 addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto);
250 return Response.ok(vspDetailsDto).build();
254 public Response getLatestVsp(final String vspId, final String user) {
255 final List<Version> versions = versioningManager.list(vspId);
256 final Version version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
257 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
258 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
259 return getVsp(vspId, version.getId(), user);
262 private void submitHealedVersion(VspDetails vspDetails, String baseVersionId, String user) {
264 if (vspDetails.getVlmVersion() != null) {
265 // sync vlm if not exists on user space
266 versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion());
268 submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> {
269 throw new IllegalStateException("Certified vsp after healing failed on validation");
271 vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion());
272 } catch (Exception ex) {
273 LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex);
278 public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) {
279 VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class);
280 vspDetails.setId(vspId);
281 vspDetails.setVersion(new Version(versionId));
282 vendorSoftwareProductManager.updateVsp(vspDetails);
283 updateVspItem(vspId, vspDescriptionDto);
284 return Response.ok().build();
288 public Response deleteVsp(final String vspId, final String user) {
289 final Item vsp = itemManager.get(vspId);
290 if (!ItemType.vsp.getName().equals(vsp.getType())) {
291 throw VendorSoftwareProductsExceptionSupplier.vspNotFound(vspId).get();
294 checkIfCanDeleteVsp(vsp, user);
297 deleteVspFromStorage(vspId, user);
298 } catch (final Exception e) {
299 logDeleteFromStorageFailure(vspId, user);
300 throw VendorSoftwareProductsExceptionSupplier.deleteVspFromStorageFailure(vspId).get();
304 deleteVsp(vspId, user, vsp);
305 } catch (final Exception e) {
306 throw VendorSoftwareProductsExceptionSupplier.deleteVspFromDatabaseFailure(vspId).get();
309 return Response.ok().build();
312 private void checkIfCanDeleteVsp(final Item vsp, final String user) {
313 final String vspId = vsp.getId();
315 checkIfVspInUse(user, vspId);
317 if (isVspItemNeverCertified(vsp)) {
320 if (!isVspItemArchived(vspId, user)) {
321 throw VendorSoftwareProductsExceptionSupplier.deleteNotArchivedVsp(vspId).get();
325 private void checkIfVspInUse(final String user, final String vspId) {
326 final Optional<String> vfNameThatUsesVspOpt;
328 vfNameThatUsesVspOpt = catalogVspClient.findNameOfVfUsingVsp(vspId, user);
329 } catch (final Exception e) {
330 throw VendorSoftwareProductsExceptionSupplier.deleteGenericError(vspId).get();
332 if (vfNameThatUsesVspOpt.isPresent()) {
333 final String vfName = vfNameThatUsesVspOpt.get();
334 throw VendorSoftwareProductsExceptionSupplier.vspInUseByVf(vfName).get();
338 private boolean isVspItemArchived(final String vspId, final String user) {
339 return getVspList(null, ItemStatus.ARCHIVED.name(), user).stream().anyMatch(item -> vspId.equals(item.getId()));
342 private boolean isVspItemNeverCertified(final Item vsp) {
343 final Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified);
344 return certifiedVersionsCounter == null || certifiedVersionsCounter == 0;
347 private void deleteVspFromStorage(final String vspId, final String user) {
348 final ArtifactStorageManager artifactStorageManager = storageFactory.createArtifactStorageManager();
349 if (artifactStorageManager.isEnabled()) {
350 artifactStorageManager.delete(vspId);
351 logDeleteFromStorageAllSuccess(vspId, user);
355 private void logDeleteFromStorageFailure(final String vspId, final String user) {
356 final String message = Messages.DELETE_VSP_FROM_STORAGE_ERROR.formatMessage(vspId);
358 versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
359 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, false, message, message)
361 } catch (final Exception e) {
362 LOGGER.error("Could not log activity '{}'", message, e);
365 private void logDeleteFromStorageAllSuccess(final String vspId, final String user) {
366 final String message = String.format("VSP '%s' fully deleted from the storage", vspId);
368 versioningManager.list(vspId).forEach(version -> activityLogManager.logActivity(
369 new ActivityLogEntity(vspId, version, ActivityType.Delete_From_Storage, user, true, message, message)
371 } catch (final Exception e) {
372 LOGGER.error("Could not log activity '{}'", message, e);
376 private void deleteVsp(final String vspId, final String user, final Item vsp) {
377 updatePackageDetails(vspId);
378 versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version));
379 itemManager.delete(vsp);
380 deleteUserPermissions(vspId);
381 permissionsManager.deleteItemPermissions(vspId);
382 uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName());
383 notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE);
386 private void updatePackageDetails(final String vspId) {
387 final List<VspDetails> listVsp = new ArrayList<>();
388 versioningManager.list(vspId).forEach(version -> listVsp.add(vendorSoftwareProductManager.getVsp(vspId, version)));
389 listVsp.forEach(vspDetail ->
390 vendorSoftwareProductManager.listPackages(vspDetail.getCategory(), vspDetail.getSubCategory())
391 .stream().filter(packageInfo -> packageInfo.getVspId().equals(vspId)).collect(Collectors.toList())
392 .forEach(packInfo -> {
393 packInfo.setTranslatedFile(ByteBuffer.wrap(new byte[0]));
394 vendorSoftwareProductManager.updatePackage(packInfo);
399 private void deleteUserPermissions(String vspId) {
400 permissionsManager.listItemPermissions(vspId).forEach(itemPermissionsEntity -> {
401 Set<String> usersToDelete = new HashSet<>();
402 usersToDelete.add(itemPermissionsEntity.getUserId());
403 permissionsManager.updateItemPermissions(vspId, itemPermissionsEntity.getPermission(), new HashSet<>(), usersToDelete);
408 public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user)
410 Version version = new Version(versionId);
411 if (request.getAction() == VendorSoftwareProductAction.Submit) {
412 if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) {
413 return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build();
415 String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage();
416 Optional<ValidationResponse> validationResponse = submit(vspId, version, message, user);
417 if (validationResponse.isPresent()) {
418 ValidationResponseDto validationResponseDto = new MapValidationResponseToDto()
419 .applyMapping(validationResponse.get(), ValidationResponseDto.class);
420 return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build();
422 notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT);
423 } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) {
424 return createPackage(vspId, version);
426 return Response.ok().build();
430 public Response getValidationVsp(String user) {
431 ItemCreationDto validationVsp = retrieveValidationVsp();
432 return Response.ok(validationVsp).build();
435 private ItemCreationDto retrieveValidationVsp() {
436 synchronized (VALIDATION_VSP_CACHE_LOCK) {
437 if (cachedValidationVsp != null) {
438 return cachedValidationVsp;
440 VspRequestDto validationVspRequest = new VspRequestDto();
441 validationVspRequest.setOnboardingMethod(NetworkPackage.toString());
442 validationVspRequest.setName(VALIDATION_VSP_NAME);
444 cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER);
445 return cachedValidationVsp;
446 } catch (CoreException vspCreateException) {
447 LOGGER.debug("Failed to create validation VSP", vspCreateException);
448 Predicate<Item> validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME
449 .equals(item.getName());
450 String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException(
451 "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util"))
453 Version validationVspVersion = versioningManager.list(validationVspId).iterator().next();
454 cachedValidationVsp = new ItemCreationDto();
455 cachedValidationVsp.setItemId(validationVspId);
456 cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class));
457 return cachedValidationVsp;
463 public Response getOrchestrationTemplate(String vspId, String versionId, String user) {
464 byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId));
465 if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) {
466 return Response.status(Response.Status.NOT_FOUND).build();
468 Response.ResponseBuilder response = Response.ok(orchestrationTemplateFile);
469 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + "LatestHeatPackage.zip");
470 return response.build();
474 public Response listPackages(String status, String category, String subCategory, String user) {
475 List<String> vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId)
476 .collect(Collectors.toList());
477 List<PackageInfo> packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory);
478 packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList());
479 GenericCollectionWrapper<PackageInfoDto> results = new GenericCollectionWrapper<>();
480 MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto();
481 if (packageInfoList != null) {
482 for (PackageInfo packageInfo : packageInfoList) {
483 results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class));
486 return Response.ok(results).build();
490 public Response getTranslatedFile(String vspId, String versionId, String user) {
491 final List<Version> versions = versioningManager.list(vspId);
492 final Version version;
493 if (versionId == null) {
494 version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus())
495 .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName())))
496 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build()));
498 version = versions.stream()
499 .filter(ver -> versionId.equals(ver.getName()) || versionId.equals(ver.getId()))
501 .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId, versionId).build()));
502 if (version.getStatus() != VersionStatus.Certified) {
503 throw new CoreException(new RequestedVersionInvalidErrorBuilder().build());
506 File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version);
507 Response.ResponseBuilder response = Response.ok(zipFile);
508 if (zipFile == null) {
509 return Response.status(Response.Status.NOT_FOUND).build();
511 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName());
512 return response.build();
516 public Response getQuestionnaire(String vspId, String versionId, String user) {
517 QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId));
518 if (questionnaireResponse.getErrorMessage() != null) {
519 return Response.status(Response.Status.EXPECTATION_FAILED)
520 .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class))
523 QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto()
524 .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class);
525 return Response.ok(result).build();
529 public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) {
530 vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData);
531 return Response.ok().build();
535 public Response heal(String vspId, String versionId, String user) {
536 HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true);
537 return Response.ok().build();
541 public Response getVspInformationArtifact(String vspId, String versionId, String user) {
542 File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId));
543 Response.ResponseBuilder response = Response.ok(textInformationArtifact);
544 if (textInformationArtifact == null) {
545 return Response.status(Response.Status.NOT_FOUND).build();
547 response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName());
548 return response.build();
552 public Response listComputes(String vspId, String version, String user) {
553 Collection<ComputeEntity> computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version));
554 MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto();
555 GenericCollectionWrapper<VspComputeDto> results = new GenericCollectionWrapper<>();
556 for (ComputeEntity compute : computes) {
557 results.add(mapper.applyMapping(compute, VspComputeDto.class));
559 return Response.ok(results).build();
562 private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) {
563 Item retrievedItem = itemManager.get(vspId);
564 Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class);
566 item.setType(retrievedItem.getType());
567 item.setOwner(retrievedItem.getOwner());
568 item.setStatus(retrievedItem.getStatus());
569 item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
570 item.setCreationTime(retrievedItem.getCreationTime());
571 item.setModificationTime(new Date());
572 item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD));
573 itemManager.update(item);
576 private Optional<ValidationResponse> submit(String vspId, Version version, String message, String user) throws IOException {
577 VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
578 if (vspDetails.getVlmVersion() != null) {
579 vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()));
581 ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails);
582 Map<String, List<ErrorMessage>> compilationErrors = vendorSoftwareProductManager.compile(vspId, version);
583 if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) {
585 .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", ""));
586 return Optional.of(validationResponse);
588 versioningManager.submit(vspId, version, message);
589 activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message));
590 return Optional.empty();
593 private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) {
594 Map<String, Object> eventProperties = new HashMap<>();
595 eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName);
596 eventProperties.put(ITEM_ID, itemId);
597 if (version != null) {
598 eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName());
599 eventProperties.put(VERSION_ID, version.getId());
601 eventProperties.put(SUBMIT_DESCRIPTION, message);
602 eventProperties.put(PERMISSION_USER, userName);
603 Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId);
605 notifier.notifySubscribers(syncEvent, userName);
606 } catch (Exception e) {
607 LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId, e);
611 private Response createPackage(String vspId, Version version) throws IOException {
612 Version retrievedVersion = versioningManager.get(vspId, version);
613 if (retrievedVersion.getStatus() != VersionStatus.Certified) {
614 throw new CoreException(new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version).build());
616 PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, retrievedVersion);
617 return Response.ok(packageInfo == null ? null : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)).build();
620 private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) {
621 Optional<OrchestrationTemplateCandidateData> candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()
622 .getInfo(vspId, version);
623 if (candidateInfo.isPresent()) {
624 if (candidateInfo.get().getValidationDataStructure() != null) {
625 vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure());
627 vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName());
628 vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix());
630 OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version);
631 if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) {
632 if (orchestrationTemplateInfo.getValidationDataStructure() != null) {
633 vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure());
635 vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName());
636 vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix());
641 private boolean userHasPermission(String itemId, String userId) {
642 return permissionsManager.getUserItemPermission(itemId, userId)
643 .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false);
646 private Predicate<Item> createItemPredicate(String versionStatus, String itemStatus, String user) {
647 Predicate<Item> itemPredicate = item -> ItemType.vsp.name().equals(item.getType());
648 if (ItemStatus.ARCHIVED.name().equals(itemStatus)) {
649 itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus()));
651 itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus()));
652 if (VersionStatus.Certified.name().equals(versionStatus)) {
653 itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified));
654 } else if (VersionStatus.Draft.name().equals(versionStatus)) {
655 itemPredicate = itemPredicate
656 .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user));
659 return itemPredicate;
662 private List<Item> getVspList(String versionStatus, String itemStatus, String user) {
663 Predicate<Item> itemPredicate = createItemPredicate(versionStatus, itemStatus, user);
664 return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime()))
665 .collect(Collectors.toList());
668 private class SyncEvent implements Event {
670 private final String eventType;
671 private final String originatorId;
672 private final Map<String, Object> attributes;
673 private final String entityId;
675 SyncEvent(String eventType, String originatorId, Map<String, Object> attributes, String entityId) {
676 this.eventType = eventType;
677 this.originatorId = originatorId;
678 this.attributes = attributes;
679 this.entityId = entityId;
683 public String getEventType() {
688 public String getOriginatorId() {
693 public Map<String, Object> getAttributes() {
698 public String getEntityId() {