From 8e9c0653dd6c6862123c9609ae34e1206d86456e Mon Sep 17 00:00:00 2001 From: talig Date: Wed, 20 Dec 2017 14:30:43 +0200 Subject: Add collaboration feature Issue-ID: SDC-767 Change-Id: I14fb4c1f54086ed03a56a7ff7fab9ecd40381795 Signed-off-by: talig --- .../rest/services/VendorSoftwareProductsImpl.java | 582 ++++++++++++++------- 1 file changed, 380 insertions(+), 202 deletions(-) (limited to 'openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java') diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java index c38bf8a0ec..feffb91703 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java @@ -20,10 +20,23 @@ package org.openecomp.sdcrests.vsp.rest.services; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.util.UniqueValueUtil; +import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; +import org.openecomp.sdc.activitylog.ActivityLogManager; +import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; +import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; +import org.openecomp.sdc.activitylog.dao.type.ActivityType; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.datatypes.model.ItemType; +import org.openecomp.sdc.healing.factory.HealingManagerFactory; +import org.openecomp.sdc.itempermissions.ItemPermissionsManager; +import org.openecomp.sdc.itempermissions.ItemPermissionsManagerFactory; +import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.MdcUtil; @@ -33,25 +46,53 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerServiceName; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory; +import org.openecomp.sdc.notification.services.NotificationPropagationManager; +import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.vendorsoftwareproduct.errors.CreatePackageForNonFinalVendorSoftwareProductErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.errors.OnboardingMethodErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.PackageNotFoundErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.VersionedVendorSoftwareProductInfo; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder; +import org.openecomp.sdc.versioning.types.Item; +import org.openecomp.sdc.versioning.types.NotificationEventTypes; +import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto; +import org.openecomp.sdcrests.item.types.ItemCreationDto; +import org.openecomp.sdcrests.item.types.VersionDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VersionSoftwareProductActionRequestDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspRequestDto; import org.openecomp.sdcrests.vsp.rest.VendorSoftwareProducts; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapItemToVspDetailsDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapPackageInfoToPackageInfoDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToItem; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDescriptionDtoToVspDetails; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; -import org.openecomp.sdcrests.wrappers.StringWrapperResponse; -import org.slf4j.MDC; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @@ -60,78 +101,127 @@ import javax.ws.rs.core.Response; import java.io.File; import java.io.IOException; import java.util.Collection; +import java.util.HashMap; import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; import static org.openecomp.sdc.logging.messages.AuditMessages.SUBMIT_VSP_ERROR; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.VALIDATION_VSP_NAME; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.SUBMIT_DESCRIPTION; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_ID; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.VERSION_NAME; @Named @Service("vendorSoftwareProducts") @Scope(value = "prototype") public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { + private static final String SUBMIT_ITEM = "Submit_Item"; - private final VendorSoftwareProductManager vendorSoftwareProductManager = - VspManagerFactory.getInstance().createInterface(); + private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class); + + private static ItemCreationDto validationVsp; - private static final Logger logger = - LoggerFactory.getLogger(VendorSoftwareProductsImpl.class); + private ItemManager itemManager = ItemManagerFactory.getInstance().createInterface(); + private ItemPermissionsManager permissionsManager = + ItemPermissionsManagerFactory.getInstance().createInterface(); + private VersioningManager versioningManager = + VersioningManagerFactory.getInstance().createInterface(); + private VendorSoftwareProductManager vendorSoftwareProductManager = + VspManagerFactory.getInstance().createInterface(); + private ActivityLogManager activityLogManager = + ActivityLogManagerFactory.getInstance().createInterface(); + private NotificationPropagationManager notifier = + NotificationPropagationManagerFactory.getInstance().createInterface(); @Override - public Response createVsp(VspDescriptionDto vspDescriptionDto, String user) { + public Response createVsp(VspRequestDto vspRequestDto, String user) { MdcUtil.initMdc(LoggerServiceName.Create_VSP.toString()); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_VSP - + vspDescriptionDto.getName()); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_VSP + vspRequestDto.getName()); - OnboardingMethod onboardingMethod; + ItemCreationDto itemCreationDto; + OnboardingMethod onboardingMethod; try { - onboardingMethod = OnboardingMethod.valueOf(vspDescriptionDto.getOnboardingMethod()); + onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod()); } catch (IllegalArgumentException e) { - return handleUnknownOnboardingMethod(); + throw getUnknownOnboardingMethod(); } - switch (onboardingMethod) { case NetworkPackage: case Manual: - VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails(). - applyMapping(vspDescriptionDto, VspDetails.class); + Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class); + item.setType(ItemType.vsp.name()); + item.addProperty(VspItemProperty.ONBOARDING_METHOD, onboardingMethod.name()); + + UniqueValueUtil.validateUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName()); + item = itemManager.create(item); + UniqueValueUtil.createUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, item.getName()); + + Version version = versioningManager.create(item.getId(), new Version(), null); + + VspDetails vspDetails = + new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class); + vspDetails.setId(item.getId()); + vspDetails.setVersion(version); + vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod()); - vspDetails = vendorSoftwareProductManager.createVsp(vspDetails, user); + vendorSoftwareProductManager.createVsp(vspDetails); + versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName()); - MapVspDetailsToVspCreationDto mapping = new MapVspDetailsToVspCreationDto(); - VspCreationDto vspCreationDto = mapping.applyMapping(vspDetails, VspCreationDto.class); - return Response.ok(vspCreationDto).build(); + itemCreationDto = new ItemCreationDto(); + itemCreationDto.setItemId(item.getId()); + itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class)); + + activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, + ActivityType.Create, user, true, "", "")); + break; default: - return handleUnknownOnboardingMethod(); + throw getUnknownOnboardingMethod(); } + + return Response.ok(itemCreationDto).build(); } - private Response handleUnknownOnboardingMethod() { + private CoreException getUnknownOnboardingMethod() { ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder .getInvalidOnboardingMethodErrorBuilder(); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.ADD_VSP, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), onboardingMethodUpdateErrorCode.message()); - throw new CoreException(onboardingMethodUpdateErrorCode); + return new CoreException(onboardingMethodUpdateErrorCode); } @Override - public Response listVsps(String versionFilter, String user) { + public Response listVsps(String versionStatus, String user) { MdcUtil.initMdc(LoggerServiceName.List_VSP.toString()); - List vspList = - vendorSoftwareProductManager.listVsps(versionFilter, user); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - if (!vspList.isEmpty()) { - MapVersionedVendorSoftwareProductInfoToVspDetailsDto mapper = - new MapVersionedVendorSoftwareProductInfoToVspDetailsDto(); - for (VersionedVendorSoftwareProductInfo versionedVsp : vspList) { - results.add(mapper.applyMapping(versionedVsp, VspDetailsDto.class)); - } + Predicate itemPredicate; + if (VersionStatus.Certified.name().equals(versionStatus)) { + itemPredicate = item -> ItemType.vsp.name().equals(item.getType()) && + item.getVersionStatusCounters().containsKey(VersionStatus.Certified); + + } else if (VersionStatus.Draft.name().equals(versionStatus)) { + itemPredicate = item -> ItemType.vsp.name().equals(item.getType()) && + item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && + userHasPermission(item.getId(), user); + + } else { + itemPredicate = item -> ItemType.vsp.name().equals(item.getType()); } + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto(); + itemManager.list(itemPredicate).stream() + .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) + .forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class))); + return Response.ok(results).build(); } @@ -139,40 +229,48 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { public Response getVsp(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_VSP.toString()); + Version version = versioningManager.get(vspId, new Version(versionId)); + VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version); + vspDetails.setWritetimeMicroSeconds(version.getModificationTime().getTime()); - VspDetails vspDetails = - vendorSoftwareProductManager - .getVsp(vspId, resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), - user); - - VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); - + try { + Optional healedVersion = HealingManagerFactory.getInstance().createInterface() + .healItemVersion(vspId, version, ItemType.vsp, false); + healedVersion.ifPresent(vspDetails::setVersion); - if (vspDetails.getOldVersion() != null && !"".equals(vspDetails.getOldVersion())) { - if (Version.valueOf(versionId).equals(versionInfo.getActiveVersion())) { + if (healedVersion.isPresent() && version.getStatus() == VersionStatus.Certified) { try { - Version healedVersion = vendorSoftwareProductManager.callAutoHeal(vspId, versionInfo, - vspDetails, user); - vspDetails = - vendorSoftwareProductManager - .getVsp(vspId, resolveVspVersion(vspId, healedVersion.toString(), user, - VersionableEntityAction.Read), user); - versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); - } catch (Exception e) { - logger.error(e.getMessage(), e); + submitHealedVsp(vspId, healedVersion.get(), user); + } catch (Exception ex) { + LOGGER.error("VSP Id {}: Error while submitting version {} " + + "created based on Certified version {} for healing purpose.", + vspId, healedVersion.get().getId(), versionId, ex.getMessage()); } } + } catch (Exception e) { + LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s: %s", + vspId, versionId, e.getMessage())); } - VspDetailsDto vspDetailsDto = vspDetails == null - ? null - : new MapVersionedVendorSoftwareProductInfoToVspDetailsDto() - .applyMapping(new VersionedVendorSoftwareProductInfo(vspDetails, versionInfo), - VspDetailsDto.class); + VspDetailsDto vspDetailsDto = + new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class); + addNetworkPackageInfo(vspId, version, vspDetailsDto); return Response.ok(vspDetailsDto).build(); } + private void submitHealedVsp(String vspId, Version healedVersion, String user) + throws IOException { + Optional + validationResponse = submit(vspId, healedVersion, "Submit healed Vsp", user); + if (validationResponse.isPresent()) { + // TODO: 8/9/2017 before collaboration checkout was done at this scenario (equivalent + // to new version in collaboration). need to decide what should be done now. + throw new IllegalStateException("Certified vsp after healing failed on validation"); + } + vendorSoftwareProductManager.createPackage(vspId, healedVersion); + } + @Override public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) { @@ -180,9 +278,9 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class); vspDetails.setId(vspId); - vspDetails.setVersion(resolveVspVersion(vspId, null, user, VersionableEntityAction.Write)); + vspDetails.setVersion(new Version(versionId)); - vendorSoftwareProductManager.updateVsp(vspDetails, user); + vendorSoftwareProductManager.updateVsp(vspDetails); return Response.ok().build(); } @@ -190,60 +288,38 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { @Override public Response deleteVsp(String vspId, String user) { MdcUtil.initMdc(LoggerServiceName.Delete_VSP.toString()); - vendorSoftwareProductManager.deleteVsp(vspId, user); + vendorSoftwareProductManager.deleteVsp(vspId); return Response.ok().build(); } @Override - public Response actOnVendorSoftwareProduct(String vspId, String versionId, - VersionSoftwareProductActionRequestDto request, + public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, + String vspId, String versionId, String user) throws IOException { + Version version = new Version(versionId); switch (request.getAction()) { - case Checkout: - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkout_VSP.toString()); - vendorSoftwareProductManager.checkout(vspId, user); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CHECK_OUT_VSP + vspId); - break; - case Undo_Checkout: - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Undo_Checkout_VSP.toString()); - vendorSoftwareProductManager.undoCheckout(vspId, user); - break; - case Checkin: - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkin_VSP.toString()); - vendorSoftwareProductManager.checkin(vspId, user); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CHECK_IN_VSP + vspId); - break; case Submit: - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Submit_VSP.toString()); - ValidationResponse validationResponse = vendorSoftwareProductManager.submit(vspId, user); - if (!validationResponse.isValid()) { - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP_FAIL + vspId); - if (validationResponse.getVspErrors() != null) { - validationResponse.getVspErrors().forEach(errorCode -> logger.audit(AuditMessages - .AUDIT_MSG + String.format(SUBMIT_VSP_ERROR, errorCode.message(), vspId))); - } - if (validationResponse.getUploadDataErrors() != null) { - validationResponse.getUploadDataErrors().values().forEach(errorMessages - -> printAuditForErrors(errorMessages, vspId, SUBMIT_VSP_ERROR)); - } - - return Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapValidationResponseToDto() - .applyMapping(validationResponse, ValidationResponseDto.class)).build(); + if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM)) { + return Response.status(Response.Status.FORBIDDEN) + .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); } - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId); + String message = + request.getSubmitRequest() == null ? "" : request.getSubmitRequest().getMessage(); + Optional validationResponse = submit(vspId, version, message, user); + + if (validationResponse.isPresent()) { + ValidationResponseDto validationResponseDto = new MapValidationResponseToDto() + .applyMapping(validationResponse.get(), ValidationResponseDto.class); + return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto) + .build(); + } + + notifyUsers(vspId, version, message, user, NotificationEventTypes.SUBMIT); break; case Create_Package: - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Create_Package.toString()); - - PackageInfo packageInfo = vendorSoftwareProductManager.createPackage(vspId, - resolveVspVersion(vspId, null, user, VersionableEntityAction.Read), user); - return Response.ok(packageInfo == null - ? null - : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)) - .build(); + return createPackage(vspId, version); default: } @@ -251,21 +327,41 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { } @Override - public Response getValidationVsp(String user) - throws Exception { - String validationVspId = vendorSoftwareProductManager.fetchValidationVsp(user); - StringWrapperResponse response = new StringWrapperResponse(validationVspId); - return Response.ok(response).build(); - } + public Response getValidationVsp(String user) throws Exception { + if (validationVsp != null) { + return Response.ok(validationVsp).build(); + } + VspRequestDto validationVspRequest = new VspRequestDto(); + validationVspRequest.setOnboardingMethod("HEAT"); + validationVspRequest.setName(VALIDATION_VSP_NAME); + + try { + validationVsp = (ItemCreationDto) createVsp(validationVspRequest, user).getEntity(); + return Response.ok(validationVsp).build(); + + } catch (CoreException validationVspAlreadyExistException) { + // find validationVsp + String validationVspId = itemManager.list(item -> + ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME.equals(item.getName())) + .stream().findFirst().orElseThrow(() -> new IllegalStateException("Vsp with name %s " + + "does not exist even though the name exists according to unique value util")).getId(); + Version validationVspVersion = versioningManager.list(validationVspId).iterator().next(); + + validationVsp = new ItemCreationDto(); + validationVsp.setItemId(validationVspId); + validationVsp + .setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class)); + + return Response.ok(validationVsp).build(); + } + } @Override public Response getOrchestrationTemplate(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_Uploaded_File.toString()); byte[] orchestrationTemplateFile = - vendorSoftwareProductManager - .getOrchestrationTemplateFile(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId)); if (orchestrationTemplateFile == null) { return Response.status(Response.Status.NOT_FOUND).build(); @@ -293,24 +389,47 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { } @Override - public Response getTranslatedFile(String vspId, String versionId, String user) { + public Response getTranslatedFile(String vspId, String versionName, String user) { MdcUtil.initMdc(LoggerServiceName.Get_Translated_File.toString()); - Version version = Version.valueOf(versionId); - Version resolvedVersion = version == null - ? getVersionInfo(vspId, VersionableEntityAction.Read, user).getLatestFinalVersion() - : version; + List versions = versioningManager.list(vspId); + Version version; + if (versionName == null) { + version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus()) + .max((o1, o2) -> ((Double) Double.parseDouble(o1.getName())) + .compareTo(Double.parseDouble(o2.getName()))).orElseThrow(() -> { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), "Package not found"); + return new CoreException(new PackageNotFoundErrorBuilder(vspId).build()); + }); + } else { + version = versions.stream().filter(ver -> versionName.equals(ver.getName())) + .findFirst().orElseThrow(() -> { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_TRANSLATED_FILE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), "Package not found"); + return new CoreException(new PackageNotFoundErrorBuilder(vspId).build()); + }); + + if (version.getStatus() != VersionStatus.Certified) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_VERSION_INFO, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid requested version"); + throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + } + } - File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, resolvedVersion, user); + File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version); Response.ResponseBuilder response = Response.ok(zipFile); if (zipFile == null) { - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_FAIL + vspId); return Response.status(Response.Status.NOT_FOUND).build(); } response.header("Content-Disposition", "attachment; filename=" + zipFile.getName()); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.IMPORT_SUCCESS + vspId); return response.build(); } @@ -318,8 +437,7 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { public Response getQuestionnaire(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_Questionnaire_VSP.toString()); QuestionnaireResponse questionnaireResponse = - vendorSoftwareProductManager.getVspQuestionnaire(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId)); if (questionnaireResponse.getErrorMessage() != null) { return Response.status(Response.Status.EXPECTATION_FAILED).entity( @@ -336,16 +454,15 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Update_Questionnaire_VSP.toString()); - vendorSoftwareProductManager.updateVspQuestionnaire(vspId, - resolveVspVersion(vspId, null, user, VersionableEntityAction.Write), - questionnaireData, user); + vendorSoftwareProductManager + .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData); return Response.ok().build(); } @Override public Response heal(String vspId, String versionId, String user) { - vendorSoftwareProductManager.heal(vspId, Version.valueOf(versionId), user); - + HealingManagerFactory.getInstance().createInterface() + .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true); return Response.ok().build(); } @@ -353,8 +470,7 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { public Response getVspInformationArtifact(String vspId, String versionId, String user) { MdcUtil.initMdc(LoggerServiceName.Get_Information_Artifact.toString()); File textInformationArtifact = - vendorSoftwareProductManager.getInformationArtifact(vspId, - resolveVspVersion(vspId, versionId, user, VersionableEntityAction.Read), user); + vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId)); Response.ResponseBuilder response = Response.ok(textInformationArtifact); if (textInformationArtifact == null) { @@ -365,10 +481,11 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { return response.build(); } - public Response listCompute(String vspId, String version, String user) { + @Override + public Response listComputes(String vspId, String version, String user) { - Collection computes = vendorSoftwareProductManager.getComputeByVsp(vspId, - resolveVspVersion(vspId, version, user, VersionableEntityAction.Read), user); + Collection computes = + vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version)); MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto(); GenericCollectionWrapper results = new GenericCollectionWrapper<>(); @@ -379,91 +496,152 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { return Response.ok(results).build(); } - @Override - public Response reSubmitAll(String user) throws IOException { - - MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Re_Submit_ALL_Final_VSPs.toString()); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.RESUBMIT_ALL_FINAL_VSPS); - - List latestFinalVsps = Objects - .requireNonNull(vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), user)); - - List nonLockedLatestFinalVsps = latestFinalVsps.stream() - .filter(vsp -> - !isVspLocked(vsp.getVspDetails().getId(), vsp.getVspDetails().getName(), user)) - .collect(Collectors.toList()); - - logger.info("Removed {} VSPs out of {} from processing due to status LOCKED.\n" + - "Total number of VSPs: {}. Performing healing and resubmit for all non-Manual VSPs " + - "in submitted status.\n No need to pre-set oldVersion field", - latestFinalVsps.size() - nonLockedLatestFinalVsps.size(), latestFinalVsps.size(), - nonLockedLatestFinalVsps.size()); - - int healingCounter = 0; - int failedCounter = 0; - for (int counter = 0; counter < nonLockedLatestFinalVsps.size(); counter++) { - VersionedVendorSoftwareProductInfo versionVspInfo = nonLockedLatestFinalVsps.get(counter); - try { - final VspDetails vspDetails = versionVspInfo.getVspDetails(); - if (!OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod())) { - logger.info("Starting on healing and resubmit for VSP [{}], #{} out of total {}", - vspDetails.getName(), counter + 1, nonLockedLatestFinalVsps.size()); - reSubmit(vspDetails, user); - healingCounter++; - } - } catch (Exception e) { - failedCounter++; + private Optional submit(String vspId, Version version, String message, + String user) throws IOException { + MdcUtil.initMdc(LoggerServiceName.Submit_VSP.toString()); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId); + + ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspId, version); + Map> compilationErrors = + vendorSoftwareProductManager.compile(vspId, version); + if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) { + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP_FAIL + vspId); + if (validationResponse.getVspErrors() != null) { + validationResponse.getVspErrors().forEach(errorCode -> LOGGER.audit(AuditMessages + .AUDIT_MSG + String.format(SUBMIT_VSP_ERROR, errorCode.message(), vspId))); + } + if (validationResponse.getUploadDataErrors() != null) { + validationResponse.getUploadDataErrors().values().forEach(errorMessages + -> printAuditForErrors(errorMessages, vspId, SUBMIT_VSP_ERROR)); } + activityLogManager.logActivity( + new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, + "Failed on validation before submit", "")); + return Optional.of(validationResponse); } - logger.info("Total VSPs processed {}. Completed running healing and resubmit for {} VSPs out" + - " of total # of {} submitted VSPs. Failures count during resubmitAll: {}", - nonLockedLatestFinalVsps.size(), healingCounter, latestFinalVsps.size(), failedCounter); + versioningManager.submit(vspId, version, message); - return Response.ok().build(); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.SUBMIT_VSP + vspId); + activityLogManager.logActivity( + new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message)); + return Optional.empty(); } - private boolean isVspLocked(String vspId, String vspName, String user) { - final VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); + private void notifyUsers(String itemId, Version version, String message, + String userName, NotificationEventTypes eventType) { + Map eventProperties = new HashMap<>(); + eventProperties.put(ITEM_NAME, itemManager.get(itemId).getName()); + eventProperties.put(ITEM_ID, itemId); + + Version ver = versioningManager.get(itemId, version); + eventProperties.put(VERSION_NAME, ver.getName()); + eventProperties.put(VERSION_ID, ver.getId()); + + eventProperties.put(SUBMIT_DESCRIPTION, message); + eventProperties.put(PERMISSION_USER, userName); - if (versionInfo.getStatus().equals(VersionStatus.Locked)) { - logger.info("VSP name [{}]/id [{}] status is LOCKED", vspName, vspId); - return true; + Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); + try { + notifier.notifySubscribers(syncEvent, userName); + } catch (Exception e) { + LOGGER.error("Failed to send sync notification to users subscribed o item '" + itemId); } - logger.info("VSP Name {}, VSP id [{}], Active Version {} , Status {}, Latest Final Version {}", - vspName, vspId, versionInfo.getActiveVersion().toString(), versionInfo.getStatus(), - versionInfo.getLatestFinalVersion().toString()); - return false; } + private class SyncEvent implements Event { - private void reSubmit(VspDetails vspDetails, String user) throws Exception { - final Version versionBefore = vspDetails.getVersion(); - vspDetails.setOldVersion("true"); + private String eventType; + private String originatorId; + private Map attributes; + private String entityId; - Version finalVersion; - try { - finalVersion = - vendorSoftwareProductManager - .healAndAdvanceFinalVersion(vspDetails.getId(), vspDetails, user); - } catch (Exception e) { - logger.error("Failed during resubmit, VSP [{}] , version before:{}, version after:{}, " + - "status after:{}, with exception:{}", - vspDetails.getName(), versionBefore.toString(), vspDetails.getVersion().toString(), - vspDetails - .getVersion().getStatus().name(), e.getMessage()); - throw e; + public SyncEvent(String eventType, String originatorId, + Map attributes, String entityId) { + this.eventType = eventType; + this.originatorId = originatorId; + this.attributes = attributes; + this.entityId = entityId; + } + + @Override + public String getEventType() { + return eventType; } - logger.info("Completed healing and resubmit for VSP [{}], version before:{}, version after:" + - " {}", vspDetails.getName(), versionBefore.toString(), finalVersion); + @Override + public String getOriginatorId() { + return originatorId; + } + + @Override + public Map getAttributes() { + return attributes; + } + + @Override + public String getEntityId() { + return entityId; + } + } + + private Response createPackage(String vspId, Version version) throws IOException { + MdcUtil.initMdc(LoggerServiceName.Create_Package.toString()); + + Version retrievedVersion = versioningManager.get(vspId, version); + if (retrievedVersion.getStatus() != VersionStatus.Certified) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.CREATE_PACKAGE, ErrorLevel.ERROR.name(), + LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't create package"); + throw new CoreException( + new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version) + .build()); + } + PackageInfo packageInfo = + vendorSoftwareProductManager.createPackage(vspId, retrievedVersion); + return Response.ok(packageInfo == null + ? null + : new MapPackageInfoToPackageInfoDto().applyMapping(packageInfo, PackageInfoDto.class)) + .build(); + } + + private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) { + OrchestrationTemplateEntity orchestrationTemplateInfo = + vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version); + + vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure()); + vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName()); + vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix() == null + ? OnboardingTypesEnum.NONE.toString() + : orchestrationTemplateInfo.getFileSuffix()); + + OrchestrationTemplateCandidateData candidateInfo = + OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface() + .getInfo(vspId, version); + + //todo - remove after fix missing candidate element + if(candidateInfo == null){ + candidateInfo = new OrchestrationTemplateCandidateData(); + candidateInfo.setFileSuffix("zip"); + } + + vspDetailsDto + .setCandidateOnboardingOrigin( candidateInfo.getFileSuffix() + == null + ? OnboardingTypesEnum.NONE.toString() + : candidateInfo.getFileSuffix()); + } + + private boolean userHasPermission(String itemId, String userId) { + String permission = permissionsManager.getUserItemPermiission(itemId, userId); + return (permission != null && permission + .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())); } - private static void printAuditForErrors(List errorList, String vspId, - String auditType) { + private void printAuditForErrors(List errorList, String vspId, String auditType) { errorList.forEach(errorMessage -> { if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) { - logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), + LOGGER.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId)); } }); -- cgit 1.2.3-korg